Why variable increment function does not work in AngularJS? Am I not accessing the variable correctly?

1

Hello. I need to change the value of a variable in angularJS but I'm encountering the following problem: "Can not set property 'quantity' of undefined".

When I click the add button, I need the quantity variable contained in commodity1 to be incremented by 1.

html button:

<button ng-show="someAdicionar" class="add" ng-click = "adicionar();">+</button>

Below is the way I have tried and in all research the suggested solution is below.

AngularJS code:

.controller('mercadoriaCarrinho', function ($rootScope, $http){
		$rootScope.listademercadoria=[];

		$rootScope.mercadoria1 = {
			id: '55',
			setor: 'alimento',
			foto: 'Produtos/Produto (55).jpg',
			descr: 'Macarr�o Renata',
			de: 15,
			por: 12,
			mercadoria: '1',
			quantidade: 1
		}
		$rootScope.listademercadoria.push($rootScope.mercadoria1);

		$rootScope.adicionar = function (){
			{	  
				$rootScope.listademercadoria.mercadoria1.quantidade=$rootScope.listademercadoria.mercadoria1.quantidade+1;
			}						
		}
});            

I note that other functions, other buttons parallel to it, are working correctly, but only this function has this problem.

    
asked by anonymous 22.09.2017 / 18:47

1 answer

4

You are trying to access a position of array by the name of the variable where values are defined. To access an item of array you must use the position, or change to a Object :

$rootScope.listademercadoria = {};

// ... Definição do objeto

$rootScope.listademercadoria.mercadoria1 = $rootScope.mercadoria1;

Or:

$rootScope.adicionar = function (){
  $rootScope.listademercadoria[0].quantidade = $rootScope.listademercadoria[0].quantidade + 1;
}

Note: Using $rootScope to store variables is not a good practice. If you want to share data with other controllers use a service or factory .

    
22.09.2017 / 19:03