在已经存在的应用中添加angular应用并传输数据

Add angular app in already existing app and transfer data

本文关键字:应用 angular 传输 数据 添加 存在      更新时间:2023-09-26

我试图在已经存在的jquery应用程序中添加angular应用程序。假设我有一个简单的按钮在html.
我试图加载角应用程序和运行控制器代码上的按钮点击。我使用angular.bootstrap(document, ['myApp'])手动加载angular应用程序。我也试图通过一些数据从jquery到角应用程序。这是可能的吗?

看一看-

<!DOCTYPE html>
<html>
<head lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <title>jA</title>
</head>
<body>
<button id="myButton" value="25">Hello world</button>
</body>
<script>
    angular.module('myApp', [])     // I defined the angular app.
            .controller('MyController', ['$scope', function ($scope) {
                console.log('Hello world');  // This should run on button click.
            }]);
    $(document).ready(function () {
        $("#myButton").click(function(){
            var some_value = '25';   //value i am trying to pass to angular app to use in angular app.
            angular.bootstrap(document, ['myApp']); //load angular app
        });
    });
</script>
</html>

jQueryAngularJS不会直接"对话",但是Angular会"看到"你拥有的任何其他原生javascript,所以让我们说——如果你定义了一个全局变量,并在AnuglarjJS访问它时通过jQuery修改它——它可以读取并使用这个值。

给出你的例子-谁在使用/调用MyController ?

查看我为您创建的小提琴作为示例:https://jsfiddle.net/b29rng12/2/

<div id="myAngularApp">
  <button id="myButton" value="25"> click to bootstrap</button>
  <p ng-controller='MyController'>
    this section will be bind to the controller. {{ test }} and the value is {{ some_jquery_value }}
  </p>
</div>
<script>
    var some_value = '25';   //value i am trying to pass to angular app to use in angular app.
    angular.module('myApp', [])     // I defined the angular app.
            .controller('MyController', ['$scope', function ($scope) {
                console.log('Hello world');  // This should run on button click.
                $scope.test = "ricky";
                $scope.some_jquery_value = some_value;   // This is your predefined variable
            }]);

  $("#myButton").click(function(){  
    some_value = 30;
    angular.bootstrap($("#myAngularApp"), ['myApp']); //load angular app
  });
</script>

所以只是解释一下-应用程序在未启动时启动,这就是为什么你会看到{{ }}而不是values。

在你点击按钮之后(就像在你的例子中一样)-应用程序是启动的-它仍然不意味着这段代码将使用你所想到的特定controller (angular模块可以有100个控制器-那么谁将使用什么?!)所以我定义了<p ng-controller='MyController'> -是在app被引导后绑定控制器的东西。

我希望它帮助....