Angular指令加载顺序:在Controller中使用时未知的提供程序

时间:2016-10-01 22:39:36

标签: angularjs

我正在尝试使用控制器click-anywhere-but-here在我的标头HTML中使用指令navCtrl。 Angular投掷错误:

  

未知提供商:clickAnywhereButHereProvider< -

我认为这与我如何使用gulp连接JS文件有关。我用所有JS检查了连接的main.js文件,并看到navCtrl指令上面定义了clickAnywhereButHere。由于控制器根本没有使用指令,所以不确定这是否重要,只有header.html文件。

<header ng-controller="navCtrl">
  <a click-anywhere-but-here="clickedSomewhereElse()" ng-click="clickedHere()">
    <li>study</li>
  </a>
</header>

如何在抱怨之前强制标头等到clickAnywhereButHere指令加载?

修改:代码:

navCtrl.js:我已经掏出了很多不相关的代码

angular
    .module('DDE')
    .controller('navCtrl', ['$rootScope', '$location', '$scope', 'Modal', 'Auth', '$window', '$state', 'deviceDetector',
        function($rootScope, $location, $scope, Modal, Auth, $window, $state, deviceDetector) {

            $scope.clicked = '';
            $scope.clickedHere = function(){
                $scope.clicked = 'stop that';
                console.log('clicked on element');
            };
            $scope.clickedSomewhereElse = function(){
                console.log('clicked elsewhere');
                $scope.clicked = 'thanks';
            };

            $scope.headings = [
                {page: 'contact', route: '#/contact'}
            ];
        }
    ]);

clickAnywhereButHere.js指令:

angular.module('DDE')
.directive('clickAnywhereButHere', function($document, clickAnywhereButHereService){
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            var handler = function(e) {
                e.stopPropagation();
            };
            elem.on('click', handler);

            scope.$on('$destroy', function(){
                elem.off('click', handler);
            });

            clickAnywhereButHereService(scope, attr.clickAnywhereButHere);
        }
    };
});

clickAnywhereButHereService.js服务:

angular.module('DDE')
.factory('clickAnywhereButHereService', function($document){
    var tracker = [];

    return function($scope, expr) {
        var i, t, len;
        for(i = 0, len = tracker.length; i < len; i++) {
            t = tracker[i];
            if(t.expr === expr && t.scope === $scope) {
                return t;
            }
        }
        var handler = function() {
            $scope.$apply(expr);
        };

        $document.on('click', handler);

        // IMPORTANT! Tear down this event handler when the scope is destroyed.
        $scope.$on('$destroy', function(){
            $document.off('click', handler);
        });

        t = { scope: $scope, expr: expr };
        tracker.push(t);
        return t;
    };
});

指令和服务都出现在我的min文件中:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要考虑your JS is minified

这一事实

所以改变这个

.directive('clickAnywhereButHere', function($document, clickAnywhereButHereService){

到这个

.directive('clickAnywhereButHere', 
  ['$document', 'clickAnywhereButHereService', 
  function($document, clickAnywhereButHereService){ 
   //... 
  }])