I am trying to write a small angular application for an online store.

Now in the application, one ng-repeat directive passes through all the goods in the category, and when the user presses the buy button, the product index - $index sent to the controller, and the fact of purchase is recorded in the model.

I want the application to have the possibility of splitting the goods into categories with the possibility of sending the category number and product number in the category to the controller, but I don’t know if it is possible to get both indices in different variables in an angular .

I would be grateful for your tips.

    2 answers 2

    It is possible to use simultaneously indexes of ng-repeat nested. To do this, each of them in ng-init must be assigned an alias.
    For example:

     <div ng-repeat="category in categories" ng-init="categoryIndex=$index"> <div ng-repeat="product in category.products" ng-init="productIndex=$index"> category index: {{categoryIndex}}<br/> product index: {{productIndex}} </div> </div> 

    Reference to the example in the documentation for the directive ng-init

    • It is easier to use the call to the external $ index through $ parent. $ parent. $ index - Dmitry Rodevich
    • @ Dmitry Rodevich, not easier, you always need to know who the guy is. - Grundy

    It is not clear how the categories with products are implemented in you, but all actions can be entered in by clicking on the Buy goods button. For example, as follows:

    HTML

     <ul> <li ng-repeat="product in products"> // some product code.. <button ng-click="addProduct($index, product.id, product.cat.id)"> Купить продукт </button> </li> </ul> 

    Js

     app.controller('productCtrl', [function(){ $scope.cart = []; //корзина $scope.addProduct = function(index, productId, catId) { $scope.cart[index] = {'product':productId, 'cat':catId}; }; }]); 

    It is also possible to get both indexes into different variables by clicking on the button ( $scope.productId and $scope.productCatId are variables from the controller osprey):

     // ... <button ng-click="productId=product.id; productCatId=product.cat.id;"> Купить продукт </button> // ... 

    Finish the details according to your implementation.