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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With