AngularJS 中启动多个 ng-app 的问题

最近正在学习 AngularJS,在编写一个小 Demo 程序时遇到一个问题,就是当在单个页面上加载了多个 ng-app 时,只有第一个会起作用。

查询后找到答案:在 angular 页面中,每一个 HTML 页面只有一个 ng-app 会被自动装载。

所以我们有几种方案来解决这个问题。

  1. 可以简单的将多个 ng-app 合并成为一个根模块。

  2. 可以手动装载除了第一个以外的多个 ng-app。

 

ng-app 是 angular 中的一个十分重要的标签。一个 ng-app 应当对应一块业务逻辑,所以一个页面是可能需要使用多个模块的。为了避免不同模块间代码的耦合,我个人更偏向于第二种做法。代码如下:

    <div id="app1div" ng-app="myApp1" ng-controller="personCtrl">
        <p>personCtrl</p>
        First name: <input type="text" ng-model="firstName"><br>
        Last Name: <input type="text" ng-model="lastName"><br>
        Full Name: {{fullName()}}
    </div>

    <br><br>
    <div id="app2div" ng-app="myApp2" ng-controller="personCtrl">
        <p>personCtrl</p>
        First name: <input type="text" ng-model="firstName"><br>
        Last Name: <input type="text" ng-model="lastName"><br>
        Full Name: {{fullName()}}
    </div>

    <script>
        var app1 = angular.module('myApp1', []);
        var app2 = angular.module('myApp2', []);

        app1.controller('personCtrl', function($scope){
            $scope.firstName = 'Aaron';
            $scope.lastName = 'S';
            $scope.fullName = function(){ return $scope.firstName + $scope.lastName; }
        });

        app2.controller('personCtrl', function($scope){
            $scope.firstName = 'Andy';
            $scope.lastName = 'W';
            $scope.fullName = function(){ return $scope.firstName + $scope.lastName; }
        });
        angular.bootstrap(document.getElementById("app2div"), ['myApp2']);
    </script>

 

posted @ 2016-01-24 18:31  赵小吉  阅读(6016)  评论(1编辑  收藏  举报