Create angular variable in html

Asked

Viewed 3,038 times

3

Hello!

I have a loop (ng-repeat) in my html file and would like to save its index in a variable to be able to pass parameter to a function.

Does anyone have an idea how I can do that?

Follow the code in the View:

<div class="lista_cores">
    <div class="opcao_tamanho col-xs-12" ng-repeat="tamanho in vm.tamanho">
    {{vm.index = $index}}
        <div class="lista_cores" ng-repeat="cor in tamanho.cor track by $index">
            <button type="button" class="btn_remove" ng-click="vm.removeCor(vm.index, $index)"><span class="glyphicon glyphicon-remove"></span></button>
        </div>
        <button type="button" class="btn_adiciona" ng-click="vm.addCor($index)">Adicionar cor</button>
    </div>
    <button type="button" class="btn_remove" ng-click="vm.removeTamanho($index)"><span class="glyphicon glyphicon-remove"></span></button>
</div>
<button type="button" class="btn_adiciona" ng-click="vm.addTamanho($index)">Adicionar tamanho</button>

Function in the Controller:

vm.tamanho = [{
        "nome_produto_tamanho": "",
        "cor": [{
            "nome_produto_cor": ""
        }]
    }];
    vm.addTamanho = function(index){
        vm.tamanho.push({
            "nome_produto_tamanho": "",
            "cor": [{
                "nome_produto_cor": ""
            }]
        });
    }
    vm.removeTamanho = function(index) {
        vm.tamanho.splice(index, 1);
    };

    vm.cores = {
        "nome_produto_cor": ""
    };
    vm.addCor = function(id_tamanho){
        vm.tamanho[id_tamanho].cor.push(vm.cores);
    }
    vm.removeCor = function(id_tamanho, index) {
        console.log(index);
        console.log(id_tamanho);
        vm.tamanho[id_tamanho].cor.splice(index, 1);
    };

The code has been greatly simplified, but that’s basically what matters.

The user can add color and size by clicking on a button and remove too, my problem is when removing an added color as I need the size id in order to be able to then erase the color.

  • could [Edit] your question and add how is your current code?

  • @David, I entered my code

  • Question - why not pass the full object as parameter?

  • because I don’t have an id inside the object

1 answer

0


I managed to solve the problem as follows: I put a div with display: none and created an empty variable within the json, called "id_Array", which I fill in as follows: {{tamanho.id_array = $index}}, just below the first ng-repeat, hence as this code is inside the None display, it will not appear on the screen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.