这是我的JS代码。
angular.module('myApp', [])
.controller("myController", [function () {
this.master = [];
this.addUser = function(user) {
this.master.push(user)
};
this.removeUser = function(user) {
var indexToRemove = this.master.indexOf(user);
this.master.splice(indexToRemove,1)
}
this.reset = function() {
this.user = this.master[this.master.length - 1];
}
}])
这是我的HTML部分。
<body ng-app="myApp" ng-controller="myController as Cntrl">
<form>
Name: <input type="text" ng-model="user.name" /> <br />
Email: <input type="email" ng-model="user.email" /> <br />
Gender: <input type="radio" ng-model="user.gender" value="male" /> Male
<input type="radio" ng-model="user.gender" value="female" /> female <br /> <br />
<input type="button" ng-click="Cntrl.addUser(user)" value="Add User">
<input type="button" ng-click="Cntrl.reset()" value="Reset User">
</form>
<div ng-repeat="users in Cntrl.master track by $index">
<span ng-click="Cntrl.removeUser(users)" >X</span> <pre>{{users | json}}</pre>
</div>
</body>
我能够添加新用户和删除选定的用户。但是每当我添加新用户时,数组中所有旧用户的属性都会更新为新添加的用户的属性。
请解释一下我在这里犯的错误。
所有推入数组的用户都是同一个,并删除更好的使用索引,ng-click = " Cntrl.removeUser(美元指数)"
angular.module('myApp', [])
.controller("myController", [
function() {
this.master = [];
this.user = this;
//use this.user
this.addUser = function() {
this.master.push(this.user)
this.user = {}
};
//use index
this.removeUser = function(index) {
this.master.splice(indexToRemove, 1)
}
this.reset = function() {
this.user = this.master[this.master.length - 1];
}
}
])
你正在给用户引用主数组,并且由于两种方式的数据绑定你的值更新,你可以试试这个,将工作
修改你的addUser方法,如下所示
this.addUser = function(user) {
this.master.push(angular.copy(user));
};
angular copy会创建对象的深度拷贝,参见docs https://docs.angularjs.org/api/ng/function/angular.copy
https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/因为已经有3篇文章回答了你的问题。但我我猜在虚拟机上有一些严重的逻辑误解您正在尝试在代码中实现的方法。通过这个程序现在正在工作,但我强烈建议你通过约翰爸爸的教程,然后再继续你的解决方案。这样就清楚了你的基本原理,让你明白为什么它不起作用之前。