I searched a lot and tried different things. But nothing worked so far.
My task is, to add a function from scope in a ng-class attribute via a directive in angular.
I have the following tag:
<table class="table">
<tr>
<td>Content 1</td>
<td>Content 2</td>
</tr>
</table>
And with the attribute to append it results:
<table class="table" data-ng-class="getTableClass()">
<tr>
<td>Content 1</td>
<td>Content 2</td>
</tr>
</table>
My directive:
angular.module('app', []).directive('table', [ function () {
return {
restrict: 'C',
replace: false,
controller: function($scope){
$scope.getTableClass = function(){
console.log("inner controller");
return "green";
};
},
compile: function (elem, attr) {
return {
pre: function preLink(scope, elem, attrs, controller) {
elem.attr("data-ng-class", "getTableClass()");
},
post: function postLink(scope, elem, attrs, controller) {}
}
}
};
}])
So far everything worked. If I programm this hard without a directive, the additional class gets appended. But if I do it with a directive, the attribute doesn't get evaluated.
Please see my example. There are two tables. The first with the directive and the second with the hardcoded attribute.
As you can see, the second one changes the color to green, which is defined in the controller of the directive and the first one does nothing.
I'm not sure, if I'm on the right way to do this.
Edit: I found some possible solution
After I made the few changes to my code, it worked in the jsfiddle but in my realworld application it was realy slow...
Edit: (it doesn't work in my realworld application (directive inside ng-repeat))
It works without the ng-repeat..
I added the third case to my jsfiddle.
- The first case is hardcoded -> works (turns green from the designcontroller)
- The second is with directive -> works (turns blue from the datacontroller)
- The last one is with the same directive inside a ng-repeat. -> This one doesn't work.