首页 > angular.run和angular.config有什么不同?

angular.run和angular.config有什么不同?

RT, 除了在注入依赖时有些区别,还有什么其他不同?两者应该如何恰当使用?


这个就要理解ng自己的运行机制
config阶段是给了ng上下文一个针对constant与provider修改其内部属性的一个阶段
而run阶段是在config之后的在运行独立的代码块,通常写法runBlock
简单的说一下就是ng启动阶段是 config-->run-->compile/link


我感觉主要是执行顺序有区别吧,比如看的时候的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。

而且这两个单词的意思就是配置、执行,符合常理。

其他的区别就不是很清楚了。

【热门文章】
【热门文章】