当路由改变时,重新运行所有angular object指令(不仅仅是link函数)

rerun all angular object directive (not only link function) on route change

本文关键字:指令 object 不仅仅是 link 函数 angular 改变 路由 重新运行      更新时间:2023-09-26

我创建了一个指令,简单地将一些存储在。html中的div标签转换为单个元素。我注意到指令只会在页面重新加载时编译,当路由被改变时,指令不会被触发,我知道你可以使用$ routechangessuccess或$scope。watch来检测路由变化,但在我的情况下,我没有在这个目录中使用link函数,我只使用templateUrl。在路由改变时重载/重新运行这个指令的最好方法是什么?下面是我的代码;

stockfront.factory('directiveConfig', function(){
factory = {};
factory.returnConfig = {
    scope : true,
    restrict: "E",
    replace: true,
    templateUrl : "",
    template : "",
    transclude  : true,
    link  : "",
    combine: ""
};
return factory;
});
stockfront.directive("mainDiv", function(directiveConfig){
directiveConfig.returnConfig.templateUrl = "./template/mainDiv.html";
return directiveConfig.returnConfig;
});

这是我尝试过的@Valery Kozlov:

stockfront.run(function($rootScope) {
    $rootScope.routeChange = false;
    $rootScope.$on("$routeChangeSuccess", function() {
    // handle route changes
    $rootScope.routeChange = true;
    });
});

然后在html:

<main-div ng-if="$root.routeChange"><main-div>

存储在$rootScope stattransition状态中,并使用以下代码片段:

<my-dir ng-if="!$root.transitionInProgress"></my-dir>

我刚刚意识到我做错了什么检查代码....后当另一个目录被触发时,工厂的returnConfig属性在路由交换上被重写。解决方案是将工厂声明为对象,然后将returnConfig添加为原型属性,使其在每个指令安装中都是唯一的

stockfront.factory('directiveConfig', function(){
//constructor
function directiveConfig(){
}
directiveConfig.prototype.returnConfig = function (){
    return {
        scope : true,
        restrict: "E",
        replace: true,
        templateUrl : "",
        template : "",
        transclude  : true,
        link  : "",
        combine: ""
    };
};
return directiveConfig;
});

stockfront.directive("mainDiv", function(directiveConfig){
    var obj = new directiveConfig()
    var dirDefault = obj.returnConfig();
    dirDefault.templateUrl = "./template/mainDiv.html";
return dirDefault;
});