how to avoid multiple function calls in the view?

4

Using Angular, in my controller I have a function that calculates the amount of filtered items.

So:

$scope.totalConferenciasRestantes = function () {

    return $scope.solicitacoes.data.filter(function (solicitacao) {
        return solicitacao.conferido == 0;
    }).length;
};

In my view, I need to display the value of this function over and over again. But I have to call the function several times is a bad practice, since you can store the value once in a variable and reuse it if need be.

Example:

var x = y();

inserir(x);

alert('o valor de x é ' + x);

In the case of Angular, can you do this in the view?

Example:

<div ng-if='totalConferenciasRestantes() > 0'>
    Falta conferir {{ totalConferenciasRestantes() }}!
</div>

In the above case, would I have to call the view totalConferencaisRestantes only once?

    
asked by anonymous 20.02.2017 / 17:47

1 answer

4

Why not run directly in the view?

In the example below, a bind in the view is used for:

  • Filter the items collection by removing all checked items:
  • Use the resulting collection and count the number of members.

angular.module('myApp', [])
.controller('myController', function($scope){
  $scope.items = [
    {idade: 27, nome: 'Wallace', marcado: true},
    {idade: 28, nome: 'Wallace2', marcado: true},
    {idade: 29, nome: 'Wallace3', marcado: false},
    {idade: 30, nome: 'Wallace4', marcado: false},
  ]; 

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><divng-app="myApp">
  <div ng-controller='myController'>
    <div ng-repeat="i in items">
      <input type="checkbox" ng-model="i.marcado"/>{{i}}
    </div>
    
    <br/>
    
    Total de itens não marcados: {{(items | filter: {marcado:false}).length }}
    
  </div>
</div>
    
20.02.2017 / 17:58