Search code examples
javascriptangularjsangularjs-ng-repeatdeep-linking2-way-object-databinding

Bind value to object property, in an object, in an array, AngularJS


Ok, heres the pickle:

Im using ng-repeat to iterate through the menu items:

<!-- start the list/loop -->
<ion-list ng-repeat="this in menuItems.items track by $index" type="item-text-wrap">

    <a class="item" ng-click="addToCart({{this}})">{{this.name}}
        <span class="badge badge-stable">{{theCart[$index].product.qty}}</span>
    </a>

</ion-list>
<!-- end the list/loop -->

The problem arises when I try to get the value out of the item in the cart 'theCart[$index].product.qty' since the $index is not bound to any particular item, just the position in the array. I need to get to a unique identifier 2 objects deep in the array so I can be sure to get the correct values with the two-way data binding Angular is so nice to provide.

theCart: [{
    product: {
        id: 1,
        section: 'sides',
        name: 'mayo',
        price: 7,
        outOfStock: '',
        qty: 1
    }
}, {
    product: {
        id: 0,
        section: 'sides',
        name: 'ranch',
        price: 6,
        outOfStock: '',
        qty: 1
    }
}];

Thanks in advance for any insight.


Solution

  • I'm not sure if I have understood your question properly.

    But assuming that menuItems.items is an array of products that for some reason its items don't have the property qty and that theCart is a different array of products in which its items do have the property qty. And that what you want is to get the available quantity of the product that you are iterating from the array theCart, you could do it using the filter 'filter', like this:

    <ion-list ng-repeat="item in menuItems.items" type="item-text-wrap">
        <a class="item" ng-click="addToCart(item.id)">{{item.name}}
            <span class="badge badge-stable">
               {{(theCart | filter:{product:{id:item.id} })[0].product.qty}}
            </span>
        </a>
    </ion-list>
    

    I must say that this is a very ugly way to do it, I wouldn't recommend doing it like this to anyone. It would be much better to generate a "joined array" of those 2 arrays in the controller and to iterate that "joined array" instead.