How to avoid multiple function calls in the view?

Asked

Viewed 312 times

4

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

Thus:

$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 necessary.

Example:

var x = y();

inserir(x);

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

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

Example:

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

In the above case, it would be like calling in the view totalConferencaisRestantes only once?

1 answer

4

Why not run directly in the view ?

In the example below a bind in the view is used to:

  • Filter the collection items, removing all marked 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>
<div ng-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>

  • 1

    Good... you can even do contagem_de_items = (items | filter: {marcado: false}).length

Browser other questions tagged

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