AngularJS - 使用 ng-repeat 的动态指令 [英] AngularJS - Dynamic Directives using ng-repeat
问题描述
我花了一段时间试图找到一个优雅的解决方案,虽然我有一个有效"的解决方案,但它并不是最简单或正确的做事方式.
所以,我的问题是...如何动态加载指令!对于某些情况,下面是我希望我能够逃脱它的方式!除了模板加载之外,我没有包含路由或任何其他内容,并且我使用 ng-controller 分配了以下控制器.
app.js
angular.module('myApp', []).controller('someController', ['$scope', function($scope) {$scope.directives = ['myDirectiveA', 'myDirectiveB'];}]).directive('myDirectiveA', function() {返回 {模板:'<p>指令 A,令人兴奋.</p>'};}).directive('myDirectiveB', function() {返回 {模板:'<p>指令 B,同样令人兴奋.</p>'};});
template.html
<div ng-repeat="指令中的指令"><x-指令></x-指令>//尝试 1<x-{{directive}}></x-{{directive}}>//尝试 2<{{'x-' + 指令}}></{{'x-' + 指令}}>//尝试 3
任何人都可以提供的任何建议将不胜感激,如果我做了任何明显愚蠢的事情,请原谅我这是我第一次使用 Angular!
希望能帮到你:
<块引用>解释一下:当你想使用时你必须 $compile 你的指令它在其他指令中,如 ngRepeat 或其他自定义指令...
angular.module('myApp', []).controller('someController', ['$scope', function ($scope) {$scope.directives = ['my-directive-a', 'my-directive-b'];}]).directive('directive', function ($compile) {返回 {限制:A",范围: {设置:="},链接:功能(范围,元素){element.html("<div class=\" "+ scope.set +" \"></div>");$compile(element.contents())(scope);}};}).directive('myDirectiveA', function () {返回 {限制:C",模板:'<p>指令 A,令人兴奋.</p>'};}).directive('myDirectiveB', function () {返回 {限制:C",模板:'<p>指令 B,同样令人兴奋.</p>'};});
<html ng-app="myApp"><头><title></title>头部><body ng-controller="someController"><div ng-repeat="指令中的指令"><div 指令集=指令"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>