从父指令或控制器中的指令名数组中呈现AngularJS指令

Thi*_*its 4 javascript angularjs

我正在尝试基于指令名称的配置数组动态呈现指令.这有可能是有角度的吗?我还希望这些渲染的指令存在于单个父dom元素中,而不是每个都获得一个新的包装器(就像使用ng-repeat一样)

http://jsfiddle.net/7Waxv/

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

myApp.directive('one', function() {
    return {
        restrict: 'A',
        template: '<div>Directive one</div>'
    }
});

myApp.directive('two', function() {
    return {
        restrict: 'A',
        template: '<div>Directive two</div>'
    }
});

function MyCtrl($scope) {
    $scope.directives = ['one', 'two'];
}

<div ng-controller="MyCtrl">
    <div ng-repeat="directive in directives">
        <div {{directive}}></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

编辑:自发布以来,我也尝试过:

.directive('parentDirective', function () {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, element) {
      scope.directives = ['one', 'two'];
      for (var i = 0; i < scope.directives.length; i++) { 
        element.prepend('<div ' + scope.directives[i] + '></div>')
      }
    }
  };
});

<div parent-directive></div>
Run Code Online (Sandbox Code Playgroud)

这样,就不会呈现前置指令中的模板.

Buu*_*yen 5

在这里我提出了(花了很长时间)...解决方案是非常通用的,你可以随意修改$scope.directives数组,指令将动态制作.您还可以指向当前作用域中的任何特定属性以从中检索指令列表.

演示链接

app.js

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

myApp.directive('one', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Directive one</div>'
    }
});

myApp.directive('two', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Directive two</div>'
    }
});

myApp.directive('dynamic', function ($compile, $parse) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, element, attr) {
      attr.$observe('dynamic', function(val) {
        element.html('');
        var directives = $parse(val)(scope);
        angular.forEach(directives, function(directive) {
          element.append($compile(directive)(scope));
        });
      });
    }
  };
});

function MyCtrl($scope) {
    $scope.directives = ['<one/>', '<two/>'];
    $scope.add = function(directive) {
        $scope.directives.push(directive);
    }
}
Run Code Online (Sandbox Code Playgroud)

的index.html

<div ng-controller="MyCtrl">
    <div dynamic="{{directives}}"></div>
    <button ng-click="add('<one/>')">Add One</button>
    <button ng-click="add('<two/>')">Add One</button>
</div>
Run Code Online (Sandbox Code Playgroud)