2

我有 2 个非常相似的 AngularJS 指令,所以我想使用一个控制器来处理它们。为了区分两个指令之间的控制器代码,我希望能够知道当前正在使用哪个指令。有没有办法告诉我?这听起来像是 AngularJS 中的一个微不足道的功能,但到目前为止我在文档中找不到它。

<div dirA ></div>
<div dirB'></div>

app.directive('dirA', function() {
    return {
        restrict: 'A',
        replace: true,
        controller: 'CommonCtrl',
    };
});

app.directive('dirB', function() {
    return {
        restrict: 'A',
        replace: true,
        controller: 'CommonCtrl',
    };
});

app.controller('CommonCtrl',
    function CommonCtrl($scope, $location, $log, $attrs) {
      // how do i know which directive is using me now???
    }
);
4

1 回答 1

2

当然,您可以在指令的控制器上设置一个属性,如果指定,它会自动注入到您的链接函数中:

这是一个笨蛋

var app = angular.module('myApp', []);

app.directive('dirA', function (){
  return {
    controller: 'CommonCtrl',
    scope: true,
    template: '<button ng-click="test()">Test A</button>',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.directiveName = 'dirA';
    }
  };
});

app.directive('dirB', function (){
  return {
    controller: 'CommonCtrl',
    scope: true,
    template: '<button ng-click="test()">Test B</button>',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.directiveName = 'dirB';
    }
  };
});

app.controller('CommonCtrl', function ($scope, $window){
  var ctrl = this;
  
  $scope.foo = 'bar';
  
  $scope.test = function (){
    $window.alert('Directive name is: ' + ctrl.directiveName);
  };
});

不过,这可能不是一个好主意。

耦合警告!

这将导致您的应用程序中的耦合稍微更紧密。因为现在您的控制器与视图之间存在依赖关系,该控制器应该封装操作您的 $scope(模型)的逻辑,因为现在您的控制器至少具有对指令名称或指令特定数据的引用。从长远来看,这将损害可测试性和可能的​​可读性。

建议:使用继承

如果情况是您与不同指令的功能略有不同,最好创建一个 CommonCtrl,然后创建一个典型地从 CommonCtrl 继承的 DirACtrl 和 DirBCtrl ......如果这有意义的话。

于 2013-10-07T19:13:36.427 回答