Angular expression if array contains

Angularjs

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

You can accomplish this with a slightly different syntax:

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

Plnkr

Solution 2 - Angularjs

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.

Solution 3 - Angularjs

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBenView Question on Stackoverflow
Solution 1 - AngularjsStewieView Answer on Stackoverflow
Solution 2 - AngularjsSlava Fomin IIView Answer on Stackoverflow
Solution 3 - AngularjsMakz23View Answer on Stackoverflow