AngularJS ng-if inside ng-repeat but only for that iteration

Viewed 19

I'm using AngularJS 1.8.2 and can't upgrade.

I have a loop like so:

<div class="cart-items" ng-repeat="item in cart.Items track by $index">
    <div>
        <div class="cart-item-quantity">
            <input keep-focus type="number" min="1" ng-min="1"  
                ng-model="cart.Items[$index].Quantity" max="{{cart.Items[$index].MaxQuantity}}"
                ng-max="cart.Items[$index].MaxQuantity"
                ng-change="update(cart.Items[$index].SKUID, cart.Items[$index].Quantity, false)" 
                ng-blur="update(cart.Items[$index].SKUID, cart.Items[$index].Quantity, true)" 
                ng-disabled="cart.Items[$index].MaxQuantity == 1" 
                id="CartItem[{{$index}}]"/>
        </div>
        <div class="cart-item-detais">
            {{cart.Items[$index].Name}}<br/>
            <span class="price" ng-bind-html="cart.Items[$index].UnitPriceTotalFormatted | trustHtml"></span>
        </div>
        <div ng-if="CartForm.$invalid" class="red"> <------- THIS --------->
          error message here
        </div>
    </div>
</div>

I'm trying to cover the edge case where the input max attribute is overriden by the keyboard but this shows the error message under each cart item. Is there something like ng-if="CartForm.#CartItem[{{$index}}].$invalid" and only have it show up in that iteration?

I know this can be done in javascript if needs be but would rather keep it angular if possible.

1 Answers

You need to name your input fields with their index; something like this:

<input type="number" name="someInput_{{$index}}" />
<div ng-if="(Form['someInput_{{$index}}'].$touched || Form.$submitted) && Form['someInput_{{$index}}'].$invalid">
    <span ng-if="Form['someInput_{{$index}}'].$error.max">Some input exceeded max value!</span>
</div>
Related