Search code examples
angularjsng-controller

How to loop through an array in Angular js


HTML View

  <div ng-app="myApp" ng-controller="myCtrl">
    Hi <span ng-click="changeName()" style="cursor: pointer;">{{firstname}}</span>
    </div>

Model and Controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "Name 1";
    $scope.changeName = function() {
        $scope.firstname = "Name 2";
    $scope.changeName = function() {
        $scope.firstname = "Name 3";
     $scope.changeName = function() {
        $scope.firstname = "Name 4";
       $scope.changeName = function() {
        $scope.firstname = "Name 5";
    }
      }
}
}
});

Now the output is "Hi Name 1" Here Name 1 is clickable, when it's clicked Name 2 is shown..like that till Name 5. But I need to loop it. When Name 5 is clicked Name 1 should be shown again.

I'm bad in english. Please help. View it in Plunker


Solution

  • Try this solution:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        var names = ['a', 'b', 'c'];
        var counter = 0;
        $scope.changeName = function(){
            $scope.firstname = names[counter++ % names.length]; 
        }
        $scope.changeName();
    });