AngularJS - 使用ng-repeat的动态指令

时间:2016-01-07 18:57:41

标签: javascript angularjs

我花了一段时间试图找到一个优雅的解决方案,而我有一个解决方案,并且可以使用'它并不像最简单或最正确的做事方式。

所以,我的问题是......我怎样才能动态加载指令!在某些情况下,下面是我希望我能够侥幸逃脱的方式!我没有包含路由或除模板加载之外的任何内容,我将以下控制器分配给ng-controller。

app.js

angular.module('myApp', [])

.controller('someController', ['$scope', function($scope) {
  $scope.directives = ['myDirectiveA', 'myDirectiveB'];
}])

.directive('myDirectiveA', function() {
  return {
    template: '<p>Directive A, exciting.</p>'
  };
})

.directive('myDirectiveB', function() {
  return {
    template: '<p>Directive B, equally as exciting.</p>'
  };
});

template.html

<div ng-controller="someController">
  <div ng-repeat="directive in directives">

    <x-directive></x-directive> // Attempt 1
    <x-{{directive}}></x-{{directive}}> // Attempt 2
    <{{'x-' + directive}}></{{'x-' + directive}}> // Attempt 3

  </div>
</div>

任何人都可以提出的建议将不胜感激,对不起,如果我做任何明显愚蠢的事情,这是我第一次使用Angular!

1 个答案:

答案 0 :(得分:2)

我希望这可以帮到你:

  

解释:你必须在你想要使用时编译你的指令   它在其他指令中,如ngRepeat或其他自定义指令...

&#13;
&#13;
        angular.module('myApp', [])

        .controller('someController', ['$scope', function ($scope) {
            $scope.directives = ['my-directive-a', 'my-directive-b'];
        }])

        .directive('directive', function ($compile) {
            return {
                restrict: "A",
                scope: {
                    set: "="
                },
                link: function (scope, element) {
                    element.html("<div class=\" "+ scope.set +" \"></div>");
                    $compile(element.contents())(scope);
                }
            };
        })

        .directive('myDirectiveA', function () {
            return {
                restrict: "C",
                template: '<p>Directive A, exciting.</p>'
            };
        })

        .directive('myDirectiveB', function () {
            return {
                restrict: "C",
                template: '<p>Directive B, equally as exciting.</p>'
            };
        });
&#13;
<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title></title>
</head>
<body ng-controller="someController">
    
    <div ng-repeat="directive in directives">
        <div directive set="directive"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</body>
</html>
&#13;
&#13;
&#13;