RT, 除了在注入依赖时有些区别,还有什么其他不同?两者应该如何恰当使用?
我感觉主要是执行顺序有区别吧,比如看的时候的demo:
var myApp=angular.module("exampleApp", ["exampleApp.Controllers", "exampleApp.Filters", "exampleApp.Services", "exampleApp.Directives"]);
myApp.constant("startTime", new Date().toLocaleString());
myApp.config(function(startTime){
console.log("Main module config: " + startTime);
});
myApp.run(function(startTime){
console.log("Main module run: " + startTime);
})
angular.module("exampleApp.Directives", [])
.directive("highlight", function($filter){
var dayFilter = $filter("dayName");
return function(scope, element, attrs){
if(dayFilter(scope.day) == attrs["highlight"]){
element.css("color", "red");
}
}
})
var now = new Date();
myApp.value("nowValue", now);
angular.module("exampleApp.Services", [])
.service("days", function(nowValue){
this.today=nowValue.getDay();
this.tomorrow=this.today + 1;
})
.config(function(){
console.log("Services module config: (no time)");
})
.run(function(startTime){
console.log("Services module run: " + startTime);
})
然后控制台输出结果:
都是最先执行config,然后是run。
而且这两个单词的意思就是配置、执行,符合常理。
其他的区别就不是很清楚了。
执行顺序不同:
config先执行,run后执行。
注入的服务也有区别:
config可以注入$stateProvider, $urlRouterProvider, $controllerProvider, $provide, $httpProvider等等provider
run可以像controlle一样注入service,例如配置公共变量等
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
这个就要理解ng自己的运行机制
config阶段是给了ng上下文一个针对constant与provider修改其内部属性的一个阶段
而run阶段是在config之后的在运行独立的代码块,通常写法runBlock
简单的说一下就是ng启动阶段是 config-->run-->compile/link