對於一般的使用者來說,AngularJS的ng-app都是手動綁定到某個dom元素。但是在一些應用中,這樣就顯得很不方便了。
綁定初始化
通過綁定來進行angular的初始化,會把js代碼侵入到html中,但是對於新手使用來說,還是足夠了!
<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>
運行后,會顯示hello,angular!
手動初始化
Angular中也提供了手動綁定的api——bootstrap,它的使用方式如下:
angular.bootstrap(element, [modules], [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']);
</script>
</body>
</html>
值得注意的是:
- angular.bootstrap只會綁定第一次加載的對象。
- 后面重復的綁定或者其他對象的綁定,都會在控制台輸出錯誤提示。