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

时间:2017-03-09 05:14:46

标签: angularjs ng-controller

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

现在输出是 &#34;你好名字1&#34; 这里名称1是可点击的,当它被点击时,名称2显示为类似于名称5.但我需要循环它。单击名称5时,应再次显示名称1。

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

试试这个,首先定义一个包含所需值的数组,并在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>

答案 2 :(得分:0)

试试这个

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