我正在使用Angular 1.5,并且有一个用例,我想有条件地向HTML添加指令属性。
为了显示:
如果条件为true,则希望将指令1和指令2添加为属性。
<ng-form class="myForm" directive1 directive2>
当条件为假时,我希望将伪指令3和伪指令4添加为属性
<ng-form class="myForm" directive3 directive4>
我已经尝试直接执行条件逻辑,但这没有用:
<ng-form class="myForm" {{ condition ? directive1 directive2 :directive3 directive4 }}>
有没有人建议轻松实现这一目标?
最佳答案
您可以尝试将这些指令包装到另一个指令中。已经有答案了:
Add directives from directive in AngularJS
我从另一个答案中添加此代码:
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true,
scope: {
condition: '='
},
priority: 1000,
link: function link(scope,element, attrs) {
if(!scope.condition){
element.attr('directive1', '');
element.attr('directive2', '');
}else{
element.attr('directive3', '');
element.attr('directive4', '');
}
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
$compile(element)(scope);
}
};
});