Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular expression if array contains

Tags:

angularjs

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

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

This isn't exactly a fool proof method. Any suggestions on how I should do this?

like image 206
Webnet Avatar asked Jun 17 '13 14:06

Webnet


People also ask

How do you check if an array contains a value in AngularJS?

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found. If you want to search from end to start, use the lastIndexOf() method: var Color = ["blue", "black", "brown", "gold"]; var a = Color.

How to use expression in Angular?

AngularJS expressions can be written inside double braces: {{ expression }} . AngularJS expressions can also be written inside a directive: ng-bind="expression" . AngularJS will resolve the expression, and return the result exactly where the expression is written.


2 Answers

You can accomplish this with a slightly different syntax:

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

Plnkr

like image 100
Stewie Avatar answered Sep 22 '22 13:09

Stewie


You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!

The better approach would be to extract this logic into reusable function on your $rootScope:

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

Then, use it in your template:

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

I think everyone will agree that this example is much more readable and maintainable.

like image 42
Slava Fomin II Avatar answered Sep 21 '22 13:09

Slava Fomin II