在这个AngularJS代码中:
<!DOCTYPE html> <html> <head> <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script> <script> var app1 = angular.module('app1',[]); app1.controller('Ctrl1',function ($scope) { $scope.name = "Jack"; }); var app2 = angular.module('app2',[]); app2.controller('Ctrl2',function ($scope) { $scope.name = "Steve"; }); </script> <title>Test Controllers</title> </head> <body> <div ng-app="app1"> <div ng-controller="Ctrl1"> <span>{{name}}</span> </div> </div> <div ng-app="app2"> <div ng-controller="Ctrl2"> <span>{{name}}</span> </div> </div> </body> </html>
我有两个ng-app和两个控制器.但只有第一个似乎有效.杰克的名字显示但史蒂夫没有.为什么?
显示问题的JSFiddle在这里:
http://jsfiddle.net/DEnB2/
原文链接:/angularjs/143412.htmlng-app指令的自动初始化仅发生一次,但您可以使用bootstrapping方法手动初始化其他模块. (见:https://docs.angularjs.org/guide/bootstrap)
解决方案的JSFiddle在这里:http://jsfiddle.net/DEnB2/5/
<!DOCTYPE html> <html> <head> <script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script> <script> var app1 = angular.module('app1',function ($scope) { $scope.name = "Steve"; }); angular.element(document).ready(function() { angular.bootstrap(document.getElementById('app2'),['app2']); }); </script> <title>Test Controllers</title> </head> <body> <div ng-app="app1"> <div ng-controller="Ctrl1"> <span>{{name}}</span> </div> </div> <div id="app2"> <div ng-controller="Ctrl2"> <span>{{name}}</span> </div> </div> </body> </html>