我有一个指令定义为
Application.Directives.directive('listview', function() {
return {
restrict: 'EAC',
templateUrl: 'directives/listview/view.html'
};
});
然后想像这样从主视图中包含它
<div class="{{directiveName}}">
</div>
其中指令名称等于“listview”。然而,它不起作用。它生成以下代码,但 listview 指令未加载
<div class="listview">
</div>
但是,当我将上面生成的代码直接键入主模板时,它确实加载该指令。怎么会?我怎样才能让它发挥作用?
最佳答案
所以我找到了一个方法。你想要的是这样的东西
<div {{directiveNameInScope}}></div>
但是,这又行不通。所以我创建了一个指令来为你做这件事。它的工作原理就像
<div loaddirective="directiveNameInScope"></div>
loaddirective 指令的样子
Application.Directives.directive('loaddirective', function($compile) {
return {
restrict: 'A',
scope: { loaddirective : "=loaddirective" },
link: function($scope, $element, $attr) {
var value = $scope.loaddirective;
if (value) {
// Load the directive and make it reactive
$element.html("<div "+value+"></div>");
$compile($element.contents())($scope);
}
},
replace: true
};
});
我把它放在 github 上:https://github.com/willemmulder/loaddirective
关于angularjs - 根据 $scope 值在 View 中加载 Angular 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154180/