I'm trying to use the addClass function within the angular.js link function and I think I found a bug.
The problem:
If I have an interpolation operator ({{}}) within the class attribute of the template, then addClass will fail silently and not add the new class.
For example -
Considering this link function:
angular.module('myApp', []).directive('afterRepeat', function() {
return {
link: function(scope,element, attrs){
if (scope.$index%2==0){
element.addClass("special");
}
}
}
});
This template works and adds the class properly
<div class="item" ng-repeat="item in items" after-repeat>item {{$index}}</div>
This template doesn't
<div class="item{{$index}}" ng-repeat="item in items" after-repeat>item {{$index}}</div>
Here's a jsFiddle demonstrating the problem
I think this happens because the attribute value gets evaluated after the link function - but that doesn't make sense to me. Shouldn't the link function be the last step in the chain?
Does anyone have an idea on how to overcome this?
Two alternatives:
a) Have a method on scope which will return the appropriate class names
$scope.getClass = function(index){
var klass = 'item' + index;
if(index % 2 === 0){
klass += ' special';
}
return klass;
};
<div ng-class="getClass($index)" ng-repeat="item in items">item {{$index}}</div>
b) Make use of ng-class expression:
<div
class="{{'item'+$index}}"
ng-class="{special: $index%2==0}"
ng-repeat="item in items"
>
item {{$index}}
</div>