所以我开始学习 AngularJS,我有一个问题,为什么我需要为特定函数调用 $index 而不是更简单的代码。这是代码:
<div ng-app="myApp">
<div ng-controller='MyController'>
<div ng-repeat="people in peoples">
{{people.name}}
<button ng-click="addONe($index)" class="button"> Try it </button>
{{people.likes}}
<button ng-click="addOne()" class="button"> Try it again </button>
{{people.likes}}
</div>
</div>
这是 Js:
var app= angular.module('myApp',[]);
app.controller('MyController', function($scope) {
$scope.peoples=[
{
name: "Alek",
age:20,
likes:0
},
{
name: "Kevin",
age:20,
likes:0
}
],
$scope.addOne= function(){
$scope.peoples.likes= $scope.peoples.likes+=1
}
$scope.addONe= function(index){
$scope.peoples[index].likes+=1
}
})
我很困惑为什么我的 $scope.addOne 函数无法正常工作,以及为什么我需要在正常运行的 $scope.addONe 函数中调用 $index 。从本质上讲,为什么我必须调用该索引而不是仅仅使用其他代码,因为我没有看到其中真正的错误(尽管我是 AngularJS 的新手,所以也许我只是错过了一些东西)。
(我知道两个函数属于同一个对象,但删除 addONe 函数并仅使用 addOne 函数并不能解决问题,因为点击按钮仍然不会增加计数)。
最佳答案
您不需要,在您的情况下您只需要传递对象 person
并继续努力。
即
$scope.addOne= function(people){
people.likes += 1;
//Or without passing people you can do the below, this here will be child scope of ng-repeat
//this.people.likes += 1;
}
和
<button ng-click="addOne(people)" class="button"> Try it again </button>
当你这样做时$scope.peoples.likes = $scope.peoples.likes+1
它不会工作,因为您没有更新 likes
person
的属性(property),相反,您正在(创建和)更新 likes
数组上的属性 peoples
.
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.peoples = [{
name: "Alek",
age: 20,
likes: 0
}, {
name: "Kevin",
age: 20,
likes: 0
}],
$scope.addOne = function(people) {
people.likes += 1
}
$scope.addONe = function(index) {
$scope.peoples[index].likes += 1
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller='MyController'>
<div ng-repeat="people in peoples">
{{people.name}}
<button ng-click="addOne(people)" class="button">Try it again</button>
{{people.likes}}
</div>
</div>
关于javascript - 为什么需要使用 $index 和 "$scope.items[index]"来处理 ng-repeat 中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31279644/