如何循环遍历 Angular js 中的数组

How to loop through an array in Angular js

HTML 查看

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

模型和控制器

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";
    }
      }
}
}
});

现在输出是 "Hi Name 1" 这里 Name 1 是可点击的,当它被点击时 Name 2 显示..直到 Name 5 。但我需要循环它。单击名称 5 时,应再次显示名称 1。

我英语不好。请帮忙。 View it in Plunker

试试这个 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();
});

试试这个,首先你用你需要的值定义一个数组,然后在你的 angular 函数中创建一个条件语句

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>

试试这个

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();