繁体   English   中英

Angular JS中的依赖问题

[英]Dependency issue in Angular JS

我刚刚创建了一个新指令,但是控制台给了我一个错误。 我相信依赖项存在问题,因为该指令无法在控制器中看到方法。

我怎样才能解决这个问题?

错误信息:

错误:$ scope.resetMessages不是函数

控制器:

angular.module('modulename').controller('controllerName', ['$scope', '$location', 'Global', 'Company', function ($scope, $location, Global, Company) {

    /* A bunch of declarations and methods... */

    $scope.resetMessages = function() {
      $scope.errorMessage = null;
      $scope.successMessage = null;
    };

}]);

指示:

angular.module('modulename').directive('directiveName', function() {

    return {
        restrict: 'E',
        templateUrl: 'path/to/template.html',
        scope: {
            'Company': '&',
            'Global': '&'
        },
        controller: function($scope) {

             /*
               A bunch of methods...       
              */  

        }
    };
});

正如Anthony Chu提到的,本节创建了一个单独的范围:

    scope: {
        'Company': '&',
        'Global': '&'
    },

这意味着它并不典型地继承自父作用域,尽管父作用域可通过$parent但是,正如Anthony所提到的,这不是一个好主意,因为它在两者之间建立了耦合,您大概想与之切断首先是孤立的作用域。

在这种情况下,您根本不需要隔离的范围。 要访问Company和Global(在Controller中可以通过依赖项注入进行访问),您也可以将它们注入到指令中:

angular.module('modulename').directive('directiveName', 
    ['Global', 'Company', function (Global, Company) {
        // Return directive config here
    }]);

然后,您可以完全省略指令中的scope: (anything) ,它将是SAME范围作为控制器,或者,如有必要,您可以执行scope: true以获得原型从父级继承的新范围。 无论哪种情况, $scope.resetMessages()都可用。

这是有关不同指令范围选项便捷备忘单

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM