Angularjs从模板中的指令检测routeChangeStart

时间:2014-07-10 10:59:49

标签: angularjs angularjs-scope directive angularjs-ng-include

我有一个非常标准的指令,它存在于一个锚元素上,它解析一个字符串以查看当前路由是否与该链接匹配,例如

<a href="/dashboard" data-nav-item="dashboard">Dashboard</a>

每次路由更改时都会运行此指令(因为链接可以在更改的ng-view之外生效,因此需要在路由更改时刷新其状态),使用$ routeChangeStart。这在我的主导航中工作正常,它位于标准视图中,但如果我在包含ng的文件(如我的子导航)中使用此指令,则无法在routeChangeStart回调中运行任何代码。我尝试过注入$ rootScope,但没有区别。该指令如下:

angular.module('myApp').directive('navItem', ['$rootScope','$location', function ($rootScope, $location) {
   return {
       restrict: 'A',
       scope: false,
       link: function postLink(scope, element, attrs) {
           console.log('All directive elements execute this!');
           $rootScope.$on('$routeChangeStart', function() {
               console.log('ng-included elements work execute this!');
           });
       }
    }
}]);

如何从ng-include模板中的指令内部访问此事件?该指令运行,但只是不会选择它。

由于

1 个答案:

答案 0 :(得分:3)

我一直试图在plunker上重新创建它,但它适用于我

http://plnkr.co/edit/9hbTLxGjoTNsM44zq6rw?p=preview

app.directive('navItem', ['$rootScope','$location', function ($rootScope, $location) {
   return {
       restrict: 'A',
       scope: false,
       link: function postLink(scope, element, attrs) {
           console.log('All directive elements execute this!');
           $rootScope.$on('$routeChangeStart', function() {
               console.log('ng-included elements work execute this!');
           });
       }
    }
}]);

检查我的plunker也许你可以找到你和我的代码之间的区别