在传统的angularJS应用中,都是通过ng-app把angular应用绑定到某个dom上,这样做会把js代码入侵到html上,angular提供了手动启动的API--angular.bootstrap()。
传统的绑定初始化
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myCtrl"> {{ hello }} </div> <script type="text/javascript"> var myModule = angular.module("myApp",[]); myModule.controller("myCtrl",function($scope){ $scope.hello = "hello,angular!"; }); </script> </body> </html>
手动初始化
angular.bootstrap(element, [appName], [config]);
element: 绑定ng-app的dom元素
modules:绑定的模块名字
config: 附加的配置
<html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script> <body id="body"> <div ng-controller="myCtrl"> {{ hello }} </div> <script type="text/javascript"> var app = angular.module("bootstrapTest",[]); app.controller("myCtrl",function($scope){ $scope.hello = "hello,angular from bootstrap"; }); // angular.bootstrap(document.getElementById("body"),['bootstrapTest']); angular.bootstrap(document,['bootstrapTest']); // 浏览器加载的每个html都会对应一个document对象, 此对象是所有html中dom元素的根节点,也属于dom元素 </script> </body> </html>
注意: angular.bootstrap只会绑定第一次加载的对象,后面重复的绑定或者其他对象的绑定,都会在控制台输出错误提示