Angular expression if array contains

I am trying to add a class to an element if jobSet not been selected for approval using expressions.

 <li class="approvalUnit" ng-repeat="jobSet in dashboard.currentWork" ng-class="{-1:'approved'}[selectedForApproval.indexOf(jobSet)]"> 

This is not a completely stupid method of proof. Any suggestions on how I should do this?

+57
angularjs
Jun 17 '13 at 14:06 on
source share
3 answers

You can accomplish this with a slightly different syntax:

 ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}" 

Plnkr

+111
Jun 17 '13 at 14:39
source share

You should not overload templates with complex logic, this is bad practice. Remember to always keep this in mind!

A better approach would be to extract this logic into the reusable function on $rootScope :

 .run(function ($rootScope) { $rootScope.inArray = function (item, array) { return (-1 !== array.indexOf(item)); }; }) 

Then use it in the template:

 <li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li> 

I think everyone will agree that this example is much more readable and easy to maintain.

+15
Mar 07 '16 at 18:33
source share

Somewhere in your initialization put this code.

 Array.prototype.contains = function contains(obj) { for (var i = 0; i < this.length; i++) { if (this[i] === obj) { return true; } } return false; }; 

Then you can use it as follows:

 <li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li> 
0
Nov 09 '16 at 10:47
source share



All Articles