Reputation: 534
For one of my projects, I have a div with three conditional ng-class, looking like:
<div name="type" ng-class="{'class-one' : stringVariable != "type", 'class-two': stringVariable == "type" && booleanTrue, 'class-three': stringVariable == "type" && !booleanTrue}">My type div.</div>
This works as I want it to run, the problem being when I have several div using the same functionality:
<div name="type" ng-class="{'class-one' : stringVariable != "type", 'class-two': stringVariable == "type" && booleanTrue, 'class-three': stringVariable == "type" && !booleanTrue}">My type div.</div>
<div name="date" ng-class="{'class-one' : stringVariable != "date", 'class-two': stringVariable == "date" && booleanTrue, 'class-three': stringVariable == "date" && !booleanTrue}">My date div.</div>
<div name="name" ng-class="{'class-one' : stringVariable != "name", 'class-two': stringVariable == "name" && booleanTrue, 'class-three': stringVariable == "name" && !booleanTrue}">My name div.</div>
Again, this works but seems inefficient and unwieldy. Every time a div uses this functionality, I end up having to change the variable inside each ng-class' expression, and any future refactoring will be a major pain in the bottom.
I am trying to find a way to define a variable inside the div and then use it inside the ng-class, such as for example something looking like:
<div name="type" ng-class="{'class-one' : stringVariable != $this.name, 'class-two': stringVariable == $this.name && booleanTrue, 'class-three': stringVariable == $this.name && !booleanTrue}">My type div.</div>
Unfortunately, and maybe obviously, this doesn't work.
Is there a way to make this kind of things work?
Upvotes: 1
Views: 72
Reputation: 534
In the end, the answer was, as suggested by Tushar, to move all the logic to a separate function, and return ng-class names that way.
As a result, we have in the template:
<div ng-class="myMethod("type")">
And in the Controller:
myMethod : function(stringVariable){
if (this.$scope.stringVariable == stringVariable) {
if (this.$scope.booleanTrue) {
return 'class-two';
} else {
return 'class-three';
}
} else {
return 'class-one';
}
}
Upvotes: 0
Reputation: 3052
A quick solution could be just use scope methods inside the template instead of variables. That way your can update the internal code of the method but the method name remains same and that mostly prevents the breaking due to refactor of logic.
So you can try this :
<div name="type" ng-class="{'class-one' : isValidForType()}"
Where isValidForType is a scope method and you can also pass data to that method if you need to access something special to that div.
Upvotes: 2