AngularJS中的多个指令的一个声明

时间:2015-03-22 11:31:26

标签: javascript angularjs angularjs-directive

我正在为所有h1-h6元素创建自定义指令。所有指令主体都是相同的:它们为h-element设置了随机颜色。

这是我的工作代码 - 丑陋和干

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

angular.module('example').factory('randomColor', function () {
    return function () {
        var colors = ['#FF6A88', '#39FF82', '#7AD5D5', '#DFAF01'];
        var randomPick = parseInt(Math.random() * colors.length);
        return colors[randomPick];
    };
});


angular.module('example').directive('h1',['randomColor', function (randomColor) {
    return {
        restrict: 'E',
        link: function (scope, element) {
            $(element).css({ color: randomColor() });
        }
    };
}]);

angular.module('example').directive('h2',['randomColor', function (randomColor) {
    return {
        restrict: 'E',
        link: function (scope, element) {
            $(element).css({ color: randomColor() });
        }
    };
}]);

//the same for h3-h6

您可以在此处查看此代码:Plunker - DRY version

可以实现这样的目标吗?

angular.module('example').directive(['h1','h2','h3','h4','h5','h6'],['randomColor', function (randomColor) {
    return {
        restrict: 'E',
        link: function (scope, element) {
            $(element).css({ color: randomColor() });
        }
    };
}]);

3 个答案:

答案 0 :(得分:3)

你尝试过这样的事吗?

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

var fn = function(randomColor) {...};

app.directive('h1', ['randomColor', fn]);
app.directive('h2', ['randomColor', fn]);
...

答案 1 :(得分:3)

围绕它的方法很多,毕竟只是JavaScript ......

数组foreach将是一个选项,您还可以查看角度核心实际上做什么来最小化样板。

var mod = angular.module('example');
['h1','h2','h3', 'h4','h5','h6'].forEach(function(tag) {
mod.directive(tag,[ 'randomColor', function(randomColor) {
  return {
    restrict: 'E',
    link: function (scope, element) {
      //Note: for angular 1.x element is already a JQuery or JQLite object, 
      // so no need for hte $() wrapping here. 
      // You need to load JQuery before angular 
      // for it to be a full JQuery object.
      element.css({color: randomColor()});
    }
  };
}]);
});

答案 2 :(得分:0)

var mod=angular.module('example', []);

mod.factory('randomColor', function() {
    return function(){
                var colors = ['#FF6A88', '#39FF82', '#7AD5D5', '#DFAF01'];
                var randomPick = parseInt(Math.random()*colors.length);

                return colors[randomPick];
            };
});

var headerDirective=[ 'randomColor', function(randomColor) {
  return {
    restrict: 'E',
    link: function (scope, element) {
      $(element).css({color: randomColor()});
    }
  };
}];

['h1','h2','h3', 'h4','h5','h6'].forEach(function(tag) {
      mod.directive(tag,headerDirective); 
 });