-2

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

codieboie
  • 52
  • 2
  • 10

3 Answers3

1

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();
});
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • Sorry, can i get a global code. If I replace Name 1 to "abc" and Name 2 to "def"..etc. Is there a solution to make this work? – codieboie Mar 09 '17 at 05:35
0

Try this, first you define an array with your required values and create a conditional statement inside your angular function

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope) {
  $scope.nameArray = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'];
  $scope.firstname = "Name 1";
  var i = 1;
  $scope.changeName = function () {
    debugger;
    if (i < $scope.nameArray.length) {
      $scope.firstname = $scope.nameArray[i];
      i++;
    } else {
      i = 0;
      $scope.firstname = $scope.nameArray[i];
    }
  }
})
<!DOCTYPE html>
<html ng-app="myApp">
  <head>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
  </head>
  <body ng-controller="MainCtrl">
   
    Hi <span ng-click="changeName()" style="cursor: pointer;">{{firstname}}</span>
  </body>
</html>
nivas
  • 3,138
  • 3
  • 16
  • 15
0

try this

var arrayIndex = 0;
var arrayNames = ['name1','name2', 'name3', 'name4', 'name5'];
$scope.changeName = function() {
  $scope.firstname = arrayNames[arrayIndex];
  arrayIndex = arrayIndex+1>=arrayNames.length?0:arrayIndex+1;
};
$scope.changeName();
Arun Redhu
  • 1,584
  • 12
  • 16