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

4
我正在尝试根据指令名称的配置数组动态渲染指令。在Angular中是否可能实现这一点?我还希望这些已呈现指令驻留在单个父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>

编辑: 发布此文后,我还尝试了以下方法:

.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>

使用这种方法,来自预置指令的模板将不会被渲染。
2个回答

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);
    }
}

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>

1
你有没有考虑过设置 restrict: 'C' 并更新元素的类名,而不是使用 element.append?这样指令就可以添加到现有的 DOM 元素上或在创建新元素时使用。 - pedalpete

0

所以第二次尝试如果我像这样在预编译指令中使用 $compile 就会成功:

.directive('parentDirective', function($compile)
    ....
element.prepend($compile('<div ' + scope.directives[i] + '"></div>')(scope));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接