很抱歉转储,问题,我是AngularJS
和JavaScript
的新用户。我想通过点击按钮迭代收集。
<body ng-init="customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}
]">
<div class="container" ng-app="myApp" ng-controller="myCtrl" >
<div class="span12">
<h1>{{name}}</h1>
<br/>
<p>{{city}}</p>
<button type="button" name="button" value="Next" ng-click="makeIterator($scope.customers)"></button>
</div>
</div>
因此,点击Next
按钮后,我希望看到下一批客户显示。我该怎么做?
答案 0 :(得分:2)
您可以存储索引并在单击按钮
时递增它<body ng-app="myApp">
<div class="container" ng-controller="myCtrl" >
<div class="span12">
<h1>{{customers[currentCustomerIdx].name}}</h1>
<br/>
<p>{{customers[currentCustomerIdx].city}}</p>
<button type="button" name="button" value="Next"
ng-click="index = (index + 1) % customers.length"></button>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
$scope.customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}];
$scope.currentCustomerIdx = 0;
});
</script>
答案 1 :(得分:1)
PFB这样做的方法:
<body>
<div class="container" ng-app="myApp" ng-controller="myCtrl">
<div class="span12">
<h1>{{customers[counter].name}}</h1>
<br/>
<p>{{customers[counter].city}}</p>
<button type="button" name="button" value="Next" ng-click="iterate();">NEXT</button>
</div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
$scope.customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}
]
$scope.counter=0;
$scope.maxCount = $scope.customers.length - 1;
$scope.iterate = function(){
if($scope.counter == $scope.maxCount)
{
$scope.counter=0;
}
else{
$scope.counter++;
}
}
});
</script>
</body>
答案 2 :(得分:1)
您可以在控制器的作用域上存储索引,通过在按钮上绑定click事件并使用索引从customers数组中检索客户来迭代customers数组。
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.index = 0;
vm.customers = customers;
vm.customer = vm.customers[vm.index];
vm.nextCustomer = nextCustomer;
function nextCustomer() {
vm.index = vm.index + 1;
if (vm.index === vm.customers.length) {
vm.index = 0;
}
vm.customer = vm.customers[vm.index];
}
}
var customers = [
{ name: 'Name 1', city: 'City 1' },
{ name: 'Name 2', city: 'City 2' },
{ name: 'Name 3', city: 'City 3' },
];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div>
<span>Customer: </span>{{ctrl.customer.name}}
</div>
<div>
<span>City: </span>{{ctrl.customer.city}}
</div>
<button type="button" ng-click="ctrl.nextCustomer()">Next</button>
</div>
</div>