根据参数值添加角度指令

时间:2014-05-13 20:18:12

标签: html angularjs data-binding angularjs-directive

TL; DR:有没有办法根据参数值动态设置指令?类似于ng-class用于设置css元素的东西,但是一种基于范围中的值设置指令的方法。我会在范围内获得价值所以我可以打电话:

<div class="data.directiveType"></div>

data.directiveType = "my-directive"
div将成为

<div class="my-directive"></div>

和myDirective会被调用吗?

详细问题:

我想要做的是允许用户向Web应用程序添加元素,我希望根据用户点击的内容添加每个元素的指令。

我有以下指令:

app.directive("mySuperman", function(){
    //directive logic
});

app.directive("myBatman", function(){
    //directive logic
});

app.directive("myWonderWoman", function(){
    //directive logic
});

我有以下控制器

app.controller("ParentCtrl", function($scope){
    $scope.superHeros = [];

    var superman = {directiveType: "my-superman"};
    var batman = {directiveType: "my-batman"};
    var wonderWoman = {directiveType: "my-wonder-woman"}

    $scope.addBatman = function()
    {
        var batmanInstance = {}
        angular.copy(batman, batmanInstance);
        $scope.superHeros.push(batmanInstance);
    }

    $scope.addSuperman = function()
    {
        var supermanInstance = {}
        angular.copy(superman, supermanInstance);
        $scope.superHeros.push(supermanInstance);
    }

    $scope.addWonderWoman = function()
    {
        var wonderwomanInstance = {}
        angular.copy(wonderWoman, wonderwomanInstance);
        $scope.superHeros.push(wonderwomanInstance);
    }

});

在index.html中我有

<body ng-controller="ParentCtrl>
    <a ng-click="addBatman()">Add Batman</a>
    <a ng-click="addSuperman()">Add Superman</a>
    <a ng-click="addWonderWoman()">Add WonderWoman</a>

    <div ng-repeat="hero in superHeros">
        <!-- The following doesn't work, but it is the functionality I am trying to achieve -->
        <div class={{hero.directiveType}}></div>
    <div>
</body>

我想到这样做的另一种方式就是在ng-include中使用ng-repeat并将模板url添加到hero对象而不是指令类型,但我希望在那里是一种更清洁的方式,我可以更好地利用数据绑定,而不必只是调用ng-include来调用另一个指令。

1 个答案:

答案 0 :(得分:3)

您可以创建一个指令,该指令将指令作为参数添加,将其添加到元素并进行编译。然后像这样使用它:

<div ng-repeat="hero in superHeros">
  <div add-directive="hero.directiveType"></div>
</div>

这是一个基本的例子:

app.directive('addDirective', function($parse, $compile) {

  return {
    compile: function compile(tElement, tAttrs) {

      var directiveGetter = $parse(tAttrs.addDirective);

      return function postLink(scope, element) {

        element.removeAttr('add-directive');

        var directive = directiveGetter(scope);
        element.attr(directive, '');

        $compile(element)(scope);
      };
    }
  };
});

演示: http://plnkr.co/edit/N4WMe8IEg3LVxYkdjgAu?p=preview