How to increment the counter with ng-repeat?

Asked

Viewed 2,054 times

0

<div ng-repeat="column in columns">
    <div ng-if="column.new">
        {{ contador = contador + 1 }}
        <span ng-if="contador === 1">
            <div class="alert alert-danger">TESTDASDALGO</div>
        </span>
        <span ng-if="contador > 1">
            {{ contador = 0 }}
        </span>
    </div>
</div>

Values are being printed between colchetes.

Another doubt:

  • Should logic be done at the front? I have a lot of conditional stuff in my project, it will probably get very confusing... (There is another way to do)?

It is possible to do something similar to what I wrote below?

var contador = 0;
angular.forEach($scope.columns, function(column){
    if(column.new){
        contador++;
        if(contador === 1){
            include('umarquivo.html');
        }
        if(contador > 1){
            '</div>'; //fechar uma div
            contador = 0;
        }
    }
});

2 answers

1

There is no need to perform such an operation just for a line counter, as ng-repeat provides an automatically - $index:

angular.module('myApp', [])
.controller('myController', function($scope){
  $scope.paineis = ['aaaaa','bbbbb','ccccc','ddddd','eeeee','fffff']; 
});
<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 paineis'>{{$index}} - {{i}}</div>
  </div>
</div>

0

Hello,

ng-repeate provides the iteration index, so you can use this variable to help you solve your problem.

if you want to better understand ng-repeat functioning https://docs.angularjs.org/api/ng/directive/ngRepeat

<div ng-repeat="column in columns">
   <div ng-if="column.new">
       <span ng-if="$index === 1">
           <div class="alert alert-danger">TESTDASDALGO</div>
       </span>
    <span ng-if="$index > 1">
        {{ contador = 0 }}
    </span>
 </div>
</div>

Always avoid putting business logic in the view, it is responsible for the representation of the user information, always try to put views logic in the controllers

Browser other questions tagged

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