I'm trying to accomplish this: Change button icon and color class if list element is present on an array. If the object is not present, the icon will be a glyphicon-plus
with btn-success
Bootstrap class. Otherwise, there will be a glyphicon-minus
with btn-danger
class. The isSelected
function returns a boolean value indicating the presence or the absence of the object inside the list. However, every time I open my modal (Angular-UI-Bootstrap), there is a parse error from isSelected
.
How to proper set a boolean function within ng-class
directive?
<tbody>
<tr ng-repeat="ex in exams track by ex.uid" ng-class="{selected: ex.uid === selectedExam.uid}" ng-click="rowclick(ex)" ng-dblclick="pushToRemoveFromSelectedList(ex)">
<td>{{ ex.description }}</td>
<td>{{ ex.date }}</td>
<td>{{ ex.code }}</td>
<td class="hidden-sm hidden-xs">{{ ex.class }}</td>
<td>
<button type="button" ng-class="'btn btn-sm btn-success':!isSelected(ex), 'btn btn-sm btn-danger':isSelected(ex)" ng-click="pushToRemoveFromSelectedList(ex)">
<span ng-class="'glyphicon glyphicon-plus':!isSelected(ex), 'glyphicon glyphicon-minus':isSelected(ex)"></span>
</button>
</td>
</tr>
</tbody>
Just as how you wrapped your tr
element's ng-class
with {}
, you also need to do it with the ng-class
attribute for both the button
and span
elements.
<button type="button"
class="btn btn-sm"
ng-class="{'btn-success': !isSelected(ex), 'btn-danger': isSelected(ex)}"
ng-click="pushToRemoveFromSelectedList(ex)">
<span class="glyphicon"
ng-class="{'glyphicon-plus': !isSelected(ex), 'glyphicon-minus': isSelected(ex)}">
</span>
</button>
Alternatively, you can choose to use a ternary operator to toggle between two classes.
<button type="button"
class="btn btn-sm"
ng-class="isSelected(ex)? 'btn-danger': 'btn-success'"
ng-click="pushToRemoveFromSelectedList(ex)">
<span class="glyphicon"
ng-class="isSelected(ex)? 'glyphicon-minus': 'glyphicon-plus'">
</span>
</button>
An advantage in this alternative is that it only needs to invoke isSelected(ex)
twice per ng-repeat
item while the first one would trigger four invocations.