在ng-repeat中切换指令

时间:2014-01-09 13:52:14

标签: angularjs

我在控制器中有一个对象(例如directives = [{type: 'toggle'}, {type: 'phone'}])。

JavaScript代码:

app.directive('toggle', function(){});
app.directive('phone', function(){});

标记:

<div ng-repeat='directive in directives'>
    <{{directive.type}}"></{{directive.type}}>
</div>

如何在ng-repeat中切换指令?

2 个答案:

答案 0 :(得分:1)

尝试: JS:

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


.controller('mainController', function($scope){
  $scope.directivesArray = [{type: 'toggle'}, {type: 'phone'}];
})


.directive('toggle', function ($compile) {
    return {
      restrict: 'AE',
      link: function (scope, element, attrs) {
        element.append($compile("<a>I'm the toggle directive</a>")(scope));
      }
    }
})

.directive('phone', function ($compile) {
    return {
      restrict: 'AE',
      link: function (scope, element, attrs) {
        element.append($compile("<a>I'm the phone directive</a>")(scope));
      }
    }
})

.directive('test', function ($compile) {
    return {
      restrict: 'AE',
      replace:true,
      link: function (scope, element, attrs) {
        attrs.$observe('dirname',function(n){
          element.append($compile("<div " + n  + "></div>")(scope));
        })
      }
    }
})

HTML:

<div ng-repeat='directive in directivesArray'>
      <test dirname="{{directive.type}}"></test>
  </div>

这是plunker

答案 1 :(得分:1)

您可以使用angular指令 ngIf 来显示相应的指令。所以你的代码看起来像是:

<div ng-repeat='directive in directives'>
    <toggle ng-if='directive.type == "toggle"'></toggle>
    <phone ng-if='directive.type == "phone"'></phone>
</div>