继承或共享指令控制器

时间:2014-09-26 21:15:44

标签: angularjs angularjs-directive

我有两个指令:A和B.它们非常相似。我希望指令B继承指令A中的控制器。

换句话说,在A的指令定义对象中用于controller:的相同函数也需要是B指令定义对象中使用的controller:函数。

除了controller:函数的复制/粘贴之外,我如何在A和B的定义中使用相同的函数?

2 个答案:

答案 0 :(得分:1)

控制器只是常规的JS函数,因此,您可以使用原型设计:

function BaseController(){
    this.commonFunct = function(){
        ...
    }
}

function CtrlA(){
}
CtrlA.prototype = BaseController

function CtrlB(){
}
CtrlB.prototype = BaseController

这适用于controllerAs语法,当您的控制器以某个名称公开范围时,例如ctrl。然后$scope.ctrl.commonFunct(更通用,从控制器的任何地方工作)或this.commonFunct(可用于控制器的实例方法,其中this是控制器本身)可用于参考功能。

如果您将一个模块中的两个控制器声明为命名函数,则该方法有效。如果它们在不同的模块中声明,您可以使用类似mixin的方式与$controller

// Base module
(function() {
  'use strict';

  angular.module('Base', []);

  function BaseController($scope, <injectables>, that) {
    that.commonFunct = function() {
    };
  }

  angular.module('Base').controller('BaseController',
    ['$scope', '...', BaseController]);
})();

// Module that inherits functionality
(function() {
  'use strict';

  angular.module('Derived', ['Base']);

  function DerivedController($scope, $controller, ...) {
    $controller('BaseController', {
      '$scope' : $scope,
      ...
      'that' : this
    });

    // this.commonFunct is available
  }

  angular.module('Derived').controller('DerivedController',
    ['$scope', '$controller', '...', DerivedController]);
})();

MHO:我建议使用命名函数来声明控制器/服务和指令,因为它更自然,JS的做事方式。另外,我喜欢controllerAs语法,因为它有助于区分直接存储在范围内的数据(如$scope.data)和控制器的方法(它们都存储在一个范围内命名)对象,如$scope.ctrl)。

答案 1 :(得分:0)

如果我理解正确,你真的不想继承控制器。您想在两个不同的指令中使用一个控制器。 如果是这种情况,只需声明控制器函数,并将其作为函数或字符串传递给指令定义对象。

相关问题