问题
Here is my directive which has replace: true
set on directive definition
<my-custom-tag>
</my-custom-tag>
this is the directive template
<div data-ng-class="{'class1': condition1, 'class2': condition2}">
</div>
Now if the use my directive as follows it throws up error
<my-custom-tag data-ng-class="{'class3': condition3}"></my-custom-tag>
The reason being, since the template also defines a data-ng-class
attribute, the emitted HTML is as follows
<div data-ng-class="{'class3': condition3} {'class1': condition1, 'class2': condition2}"></div>
Hence the syntax error while compiling template. Any way to merge these objects ?
Plunkr, look at the browser console for the error message and inspect element to check the data-ng-class
attribute
回答1:
I saw that there is a open issue talking about this.
You can use compile
to modify the expression before the link function is triggered. Plunkr.
angular.module('directive', []).directive('myCustomTag', function() {
return {
template: "<div data-ng-class=\"{'foo': whenFoo()}\">My Custom Tag</div>",
restrict: 'E',
replace: true,
compile: function compile(tElement, tAttrs) {
tAttrs.ngClass = tAttrs.ngClass.replace(/}\s*{/g, ', ');
return function (scope, iElement, iAttrs) {
scope.whenFoo = function() {
return true;
};
};
}
};
});
来源:https://stackoverflow.com/questions/30440194/merge-ngclass-attributes-when-replace-true