是否可以在不使用ng-app的情况下运行此功能?

时间:2019-10-04 17:47:24

标签: javascript angularjs

我的AngularJS应用程序的html中有2个ng-app标签,从研究看来,这意味着只有第一个被运行。

我在这里有这种方法

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">
</script>
<script>
    var app = angular.module("MyApp", []);

    app.controller('myCtrl', function($scope, $http) {
        $http({
            method : "GET",
            url : "http://localhost:5050/get_time"
        }).then(function successCallBack(response) {
            $scope.jsonResponse = response.data;
        }, function errorCallBack(response) {
            $scope.jsonResponse = "failed"
        });
        angular.bootstrap(document.getElementById("App"), ['MyApp']);
    });
</script>
<div ng-app = "MyApp" ng-controller="myCtrl">

    <p>Response of JSON Below:</p>
    <h1>{{jsonResponse}}</h1>

</div>

您可以在此处看到此行

<div ng-app = "MyApp" ng-controller="myCtrl">

基本上我只需要我的函数就可以工作而不使用ng-app,这可能吗?

1 个答案:

答案 0 :(得分:0)

要引导第二个应用程序,请使用angular.bootstrap

<div id="app2" ng-controller="myCtrl">    
    <p>Response of JSON Below:</p>
    <h1>{{jsonResponse}}</h1>    
</div>
angular.module("MyApp", [])
.controller('myCtrl', function($scope, $http) {
    $http({
        method : "GET",
        url : "http://localhost:5050/get_time"
    }).then(function successCallBack(response) {
        $scope.jsonResponse = response.data;
    }, function errorCallBack(response) {
        $scope.jsonResponse = "failed"
    });
});

angular.element(function () {
    angular.bootstrap(document.getElementById("app2"), ['MyApp']);
});

从文档中:

  

注意事项

     

无论是自动引导还是手动引导,都需要牢记以下几点:

     
      
  • 虽然每页可以引导多个AngularJS应用程序,但我们并未针对这种情况进行积极测试。您可能会遇到问题,尤其是对于复杂的应用程序,因此建议您谨慎使用。
  •   

有关更多信息,请参见