Eric Mitjans Eric Mitjans - 1 month ago 10
AngularJS Question

Using ng-class from a nested ng-repeat

I have a nested ng-repeat list, and I want to add a class to the parent one when any item from the nested list is modified.

It looks like this:

<div ng-repeat="pa in products" ng-class="{full: vari.basket>0}">
<div ng-repeat="vari in pa.variacions">
<input type="number" ng-model="vari.basket" name="basket" min="0" max="20" step="1" ng-init="vari.basket=0">
</div>
</div>


So basically I want to add the
full
class when any of the vari items has a basket > 0.

So far is not working, what am I missing?

Answer Source

You can add a function in your controller that sets the class for your parent.

<div ng-repeat="pa in products" ng-class="{full: isFull(pa.variacions)}">
    <div ng-repeat="vari in pa.variacions">
       <input type="number" ng-model="vari.basket" name="basket" min="0" max="20" step="1" ng-init="vari.basket=0">
    </div>
</div>

In your controller:

$scope.isFull = function(variacions) {
  if (!Array.isArray(variacions)) {
    return false;
  }

  return variacions.find(vari => vari.basket > 0);
}