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

Asked

Viewed 50 times

1

Hello. I need to change the value of a variable in Angularjs but I am finding the following problem: "Cannot set Property 'quantity' of Undefined".

By clicking the button add, need the variable amount contained in market1 is increased by 1.

Html button:

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

Below the way I tried and in every search the suggested solution is this 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 emphasize that functions of another type, of other buttons parallel to this, are working correctly, however only this function is with this problem.

  • 2

    It is bad practice to store data in $rootScope

  • Thanks for the tip. Considering that I store in $Scope, would solve this my problem?

1 answer

4


Are you trying to access a position of array by the name of the variable in which the values are set. 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;
}

Observing: Use the $rootScope to store variables is not a good practice. If you want to share data with others controllers use a service or factory.

  • Thanks for the answer. It worked. Could you tell me why it’s not good practice?

  • 1

    @Guilhermesilvadeoliveira Take a look in this topic.

Browser other questions tagged

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