道招

AngularJS加载方式和angular.bootstrap

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

AngularJS加载方式和angular.bootstrap

我们一般写AngularJS时,会在html或者body、div、form等标签里面加上ng-app="myApp"之类的,这实际上就是让angular自动加载,Angular会自动找到ng-app指令,并将写有ng-app的HTML元素里面的内容作为自己的管辖范围,也就是以该元素为根。这时系统只会找第一个ng-app,如果你的代码里面有多个ng-app的话,angular只理会第一个,后面的直接无视。 如果你的代码里面没有包含ng-app,你就只能手动加载angular了,就需要用到angular.bootstrap这个函数了。 angular.bootstrap函数有两个参数,第一个参数必须,第二个为可选参数。 **使用方法:
  1. element(DOM元素):该DOM元素将作为angular的根
  2. modules(数组,数组里面的元素可以是字符、函数、数组):angular需要加载的各个模块的名字所构成的数组
返回值: 为应用新建一个注入器。 示例代码如下:
var app = angular.module("myApp", []);
var app2 = angular.module("myApp2", []);
var app3 = angular.module("myApp3", []);
console.log(app);
app.controller('myCtrl', ['$scope', function($scope) {
  $scope.test = "This is a test!"
}]);
app2.controller('myCtrl2', ['$scope', function($scope) {
  $scope.test = "A test too!"
}]);
app3.controller('myCtrl3', ['$scope', function($scope) {
  $scope.test = "I am from div3!"
}]);

angular.element(document).ready(function() {
  angular.bootstrap(document.getElementsByName('boot'), ['myApp', 'myApp2']);
  angular.bootstrap(document.getElementById("div3"), ["myApp3"]);
});
html代码
<html>
<body>
    <div name='boot' ng-controller="myCtrl">
    {{test}}
    </div>
    <div name='boot' ng-controller="myCtrl2">
    {{test}}
    </div>
    <div id='div3' ng-controller="myCtrl3">
    {{test}}
    </div>
</body>
</html>
运行结果如下: angular.bootstrap 也可以利用下面的代码实现加载三个
angular.element(document).ready(function() {
    angular.bootstrap(document), ['myApp', 'myApp2', 'myApp3']); 
});
在做项目的实战中,手动加载angular完全没有必要。
更新时间:
上一篇:浅析angular.bind下一篇:浅析angular.identity

相关文章

[转载]JQuery实现页面随滚动条滚动而动态加载内容的效果

新浪微博有这个功能,刚才思考一下 ,简单的写了一下实现方法,代码是Js的. 无可否认,这种方式应该算是web2.0的产物,在用户体验上具备很好的感受,除了微博在使用该方式外,另外我还发现有几个其 阅读更多…

关注道招网公众帐号
友情链接
消息推送
道招网关注互联网,分享IT资讯,前沿科技、编程技术,是否允许文章更新后推送通知消息。
允许
不用了