[angularjs] Angular expression if array contains

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?

This question is related to angularjs

The answer is


You can accomplish this with a slightly different syntax:

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

Plnkr


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.


Somewhere in your initialisation 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 this way:

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