AngularJS中多个指令的一个声明

One declaration for multiple directives in AngularJS

本文关键字:一个 声明 指令 AngularJS      更新时间:2023-09-26

我正在为所有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版本

有可能实现这样的目标吗

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

有很多方法可以解决它,毕竟它只是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()});
    }
  };
}]);
});

你试过这样的东西吗?

var app = angular.module('example', []);
var fn = function(randomColor) {...};
app.directive('h1', ['randomColor', fn]);
app.directive('h2', ['randomColor', fn]);
...
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); 
 });