今天下雨,阴沉沉的
今天利用angular写了些模块,突然发现自己连最原始的定义都有点模糊了,那就重新梳理一下吧:
//angular.module(name, [requires], [configFn])
var app = angular.module("myApp" , []);
app.controller('myController', function(){
})
1.module的第一个参数表示【模块名】
2.requires第二个参数表示【模块的依赖】,以数组的形式【‘A’ , ‘B’】。requires中的字符串表示依赖的模块名称。如果不是字符串,则必须是方法(或数组格式的方法),那么,这个方法就代表了一个模块。
3.参数configFn是方法或数组,负责在模块初始化时做一些配置,如果是数组,最后一个元素必须是方法。
方法configFn并不是在执行angular.module()的时候立即执行,而是当这个模块被第一次使用时,由注入器调用执行。同时,查看方法configFn中的this就会发现,这个this在浏览器中指向的是window,而不是module。而且,方法configFn只会执行一次,因此同一个angular模块不会重复配置。
我一直都是写第一个和第二个参数[](空数组),第三个参数没写过,因为没有方法要在第一次使用时就执行。
同名模块
已经初始化的angular模块保存在一个叫modules的缓存对象中,key是模块名,value是模块对象。所以,定义一个同名的模块,等于覆盖之前的模块。除此之外,不同module下的相同factory对象也会覆盖
module表示定义模块,可以定义多个,并在某个模块中进行依赖,但是在页面上定义多个模块是无效的,比如:
//页面上
<div ng-app="test"> //模块test
<div ng-controller="OuterCtrl">
<button increasea>点击 a 增加</button>
<p>a:<span ng-bind="a"></span></p>
<div ng-controller="InnerCtrl">
<button increaseb>点击 b 增加</button>
<p>a:<span ng-bind="a"></span></p>
<p>b:<span ng-bind="b"></span></p>
<button ng-click="increasea()">increase {{a}}</button>
</div>
</div>
</div>
<div ng-app="test3"> //模块test3
<div ng-controller="OuterCtrl3">
<button increasea>点击 a3 增加</button>
<p>a3:<span ng-bind="a3"></span>{{a3}}</p>
</div>
</div>
//JS上:
var app = angular.module("test", []);
app.directive("increasea", function() {
return function (scope, element, attr) {
element.on("click", function() {
scope.a++;
scope.$digest();
});
};
});
var app3 = angular.module("test3", []);
app3.controller("OuterCtrl3", ["$scope", function($scope) {
$scope.a3 = 1;
$scope.$watch("a3", function(newVal) {
console.log("a3:" + newVal);
});
$scope.$on("test", function(evt) {
$scope.a3++;
});
}]);
效果:可以看到test3并没有什么作用,是无效的
依赖上面有效,理解应该是这样的:
angular.module("moduleB", [])
.service("GreetService", function() {
return {
greet: function() {
return "Hello, world";
}
};
});
angular.module("moduleA", ["moduleB"])
.controller("TestCtrl", ["$scope", "GreetService", function($scope, GreetService) {
$scope.words = "";
$scope.greet = function() {
$scope.words = GreetService.greet();
};
}]);
//对应的HTML
<div ng-app="moduleA">
<div ng-controller="TestCtrl">
<span ng-bind="words"></span>
<button ng-click="greet()">Greet</button>
</div>
</div>
结果:
创建了两个module,在页面上只直接初始化了moduleA,但是从moduleA的依赖关系中,引用到了moduleB,所以,moduleA下面的TestCtrl,可以像引用同一个module下其他service那样,引用moduleB中定义的service。