Angular - 从同一个函数创建多个指令

时间:2014-08-18 19:18:49

标签: angularjs angularjs-directive angularjs-factory

要创建指令/控制器/工厂,您需要提供一个函数作为"注入点":

angular.module('myApp').directive('myDirective', ['dependencies', function injectionPoint(dependencies) {}]);

您可以通过Angular注册的其他功能提供injectionPoint吗?例如一个factory?我应该注意到,我已经在单独的文件中声明了所有内容,并且我正在努力做到这一点,并采用了有角度的方式。而不是创建不必要的全局变量。

具体来说,我有两个输入指令基本相同,只是使用不同的模板和隔离范围声明。

我想创建一个"指令工厂"我可以使用,比如:

function directiveFactory(scopeOverride, extraInit) {
    return function directiveInjectionPoint(depedencies) {
        return { restrict...,
                 template...,
                 scope: angular.extend({/*defaults*/}, scopeOverride),
                 link: function(...) {
                           // default stuff
                           if(angular.isDefined(extraInit)) extraInit($scope, el, attrs);
                       }
    }
}

然后我将使用:

angular.module('myApp')
    .directive('myDirective1', directiveFactory({/* new stuff */))
    .directive('myDirective2', directiveFactory({/* other stuff */, fn2...));

但是如何在Angular中注册该函数,然后在指令声明中使用它?

1 个答案:

答案 0 :(得分:1)

您可以使用这样的服务和指令:

app.factory('MyService', function() {

  var MyService = {};

  MyService.createDirective = function(scopeOverride, extraInit) {
    return {
      restrict: 'E',
      transclude: true,
      scope: scopeOverride,
      template: '<pre ng-transclude></pre>'
    };
  };

  return MyService;

});


app.directive('drzausDirective1', function(MyService) {
  return MyService.createDirective(true);
});


app.directive('drzausDirective2', function(MyService) {
  return MyService.createDirective(false);
});

http://plnkr.co/edit/BuKMXxMQ4XVlsykfrDlk?p=preview

enter image description here