How to reference the variable within HTML through AngularJS?

0

Within an ng-controller, I want a variable to appear, and it is not appearing. HTML code:

<div class="body" ng-controller="mercadoriaCarrinho as merc">
<span>Total dos produtos: {{merc.listaDoCarrinho.mercadoria.total}}</span> 
</div>

AngularJS code:

<script> angular.module('meumodulo',[])

.controller('mercadoriaCarrinho', function ($rootScope, $http){
$rootScope.listaDoCarrinho=[];
$rootScope.mercadoria = {
	id: 'id',
	setor: 'setor',
	foto: 'foto',
	descr: 'descr',
	de: de,
	por: por,
	mercadoria: '0',
	quantidade: 0,
	total: '5',
	boto: -1
}

$rootScope.listaDoCarrinho.push($rootScope.mercadoria);
});
    
asked by anonymous 26.09.2017 / 02:27

2 answers

1

The problem is that you are using $rootScope in html . Ideally, do not use $rootScope , but this to share data with view . You are also using push in array , so you can not access your variable by name, but by position. Change your controller to the following:

angular
  .module('meumodulo',[])
  .controller('MercadoriaCarrinhoController', MercadoriaCarrinhoController);

MercadoriaCarrinhoController.$inject = ['$http'];

function MercadoriaCarrinhoController($http){
  var vm = this;

  vm.listaDoCarrinho = {};
  _iniciar();

  function _iniciar() {
    var mercadoria = {
      id: 'id',
      setor: 'setor',
      foto: 'foto',
      descr: 'descr',
      de: de,
      por: por,
      mercadoria: '0',
      quantidade: 0,
      total: '5',
      boto: -1
    }

    vm.listaDoCarrinho.mercadoria = mercadoria;
  }
}

And the div in its html :

<div class="body" ng-controller="MercadoriaCarrinhoController as vm">
  <span>Total dos produtos: {{vm.listaDoCarrinho.mercadoria.total}}</span> 
</div>

If you want to keep the implementation by array change your implementation to the following:

angular
  .module('meumodulo',[])
  .controller('MercadoriaCarrinhoController', MercadoriaCarrinhoController);

MercadoriaCarrinhoController.$inject = ['$http'];

function MercadoriaCarrinhoController($http){
  var vm = this;

  vm.listaDoCarrinho = [];
  _iniciar();

  function _iniciar() {
    var mercadoria = {
      id: 'id',
      setor: 'setor',
      foto: 'foto',
      descr: 'descr',
      de: de,
      por: por,
      mercadoria: '0',
      quantidade: 0,
      total: '5',
      boto: -1
    }

    vm.listaDoCarrinho.push(mercadoria);
  }
}

And the div in its html :

<div class="body" ng-controller="MercadoriaCarrinhoController as vm">
  <span>Total dos produtos: {{vm.listaDoCarrinho[0].total}}</span> 
</div>

Use vm only for the variables you require to be printed on the screen, otherwise use var .

    
27.09.2017 / 13:59
1

Friend, when you push your variable looks like this:

[{"id":"id","setor":"setor","foto":"foto","descr":"descr","de":"de","por":"por","mercadoria":"0","quantidade":0,"total":"5","boto":-1}]

To display the total the form of access will be;

 total:{{merc.listaDoCarrinho[0]['total']}}
    
26.09.2017 / 03:13