我有一个指令,我想将一个显示值传递给它,它有条件地编译内部指令上的属性指令。
例如,
<a-directive show-it="showIt"></a-directive>
如果 showIt
为真,我希望将其替换为
<a-directive show-it="showIt">
<inner-directive value="[some expression]">
<div>[some expression evaluated]</div>
</inner-directive>
</a-directive>
在哪里
[some expression]
需要解释(我猜它需要被$compile
,但我不确定)inner-directive
在它自己的模板文件中,并且有它自己的链接函数来设置一些东西
否则,如果 showIt
为假,我希望将其替换为
<a-directive show-it="showIt">
<inner-directive></inner-directive>
</a-directive>
示例如下:
http://jsbin.com/uBIceCi/29/edit (如果您取消注释,我创建的 $compile
会创建一个无限循环 - 在前链接和后链接函数中都尝试过)。
<罢工> http://jsbin.com/uBIceCi/7/edit (老例子)
更新:
我的实际应用是想有条件的加上typeahead (需要编译)到我内部生成的指令。即,我有一个
最佳答案
您可以在指令的链接功能中选择所需的模板,如下所示
var app = angular.module('app', []);
app.controller('MainCtrl', function ($scope) {
$scope.showIt = false;
})
app.directive('aDirective', function ($compile) {
return {
restrict: 'EA',
link: function (scope, element, attrs) {
var template1 = '<div>template1</div>';
var template2 = '<div>template2</div>';
if (scope.showIt) {
element.append($compile(template1)(scope));
} else {
element.append($compile(template2)(scope));
}
},
scope: {
showIt: '='
}
}
});
在你看来:
<div ng-app="app" ng-controller="MainCtrl">
<a-directive show-it="showIt"> </a-directive>
</div>
关于javascript - 如何有条件地将属性指令添加到子指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21290748/