这是一个 fiddle :
基本上,<div data-foo-{{letterA}}></div>
都不是也不<div data-ng:model="foo-{{letterB}}"></div>
被插值。
我正在寻找一种动态加载多个内联模板之一的方法。
如果之前已经有人问过这个问题,请原谅我,但我搜索了一下却找不到。
我相信 Radim Köhler 的答案是正确的。就在发布之前,我把一些东西拼凑在一起,从另一个指令中加载指令,如下所示:
angular.module('myApp', []).directive('loadTmpl', function($compile) {
return {
restrict: 'A',
replace: true,
link: function($scope, $element, $attr) {
$element.html("<div data-card-"+$attr.loadTmpl+"></div>");
$compile($element.contents())($scope);
}
};
});
和:
<div data-load-tmpl="{{directiveName}}"></div>
我认为这是极简主义的方法,但它可能有问题,所以请看下面的答案。
最佳答案
让我们这样调整它(更新的 fiddle )。观点:
<div my-selector name="letterA"></div>
<div my-selector name="letterB"></div>
Controller :
function myCtrl($scope) {
$scope.letterA = 'bar';
$scope.letterB = 'baz';
}
这是新指令 mySelector
,包含选择器
.directive('mySelector',
[ '$templateCache','$compile',
function($templateCache , $compile) {
return {
scope: {
name: '='
},
replace: true,
template: '',
link: function (scope, elm, attrs) {
scope.buildView = function (name) {
var tmpl = $templateCache.get("dir-foo-" + name);
var view = $compile(tmpl)(scope);
elm.append(view);
}
},
controller: ['$scope', function (scope) {
scope.$watch('name', function (name) {
scope.buildView(name);
});
}],
};
}])
.run(['$templateCache', function ($templateCache) {
$templateCache.put("dir-foo-bar", '<div data-foo-bar></div>');
$templateCache.put("dir-foo-baz", '<div data-foo-baz></div>');
}])
如果你喜欢它,所有学分都转到 Render a directive inside another directive (within repeater template)和 AngularJS - Directive template dynamic ,如果你不这样做,请怪我。
关于javascript - 任何动态加载 Angular Directive(指令)的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200974/