Angularjs:复选框和ng-change [英] Angularjs: checkbox and ng-change
问题描述
我无法理解ng-change的工作原理。我有一个邀请加入拍卖的用户列表。我想用一个复选框来做这件事。如果选中该用户,则必须将其名称保存到数组中。后来我会邀请他们(我只知道怎么做)。但我不明白如何使用复选框。
我做了这样的事情:
I have problems to understand how ng-change works. I have a list of user to invite to join an auction. I want to do this with a checkbox. If the user is checked, his name has to be saved into an array. And later i will invite them(i just know how to do this). But i don't understand how to use the checkbox. I did something like this:
<ul class="list-group" ng-repeat="user in users">
<li class="list-group-item" ng-hide="user.name == profile">
<img ng-src="{{user.img}}" class="image2" >
<div class="username"> {{user.name}}</div>
<div class="userrole"> {{user.role}} </div>
<div class="usercompany">{{user.company}}</div>
<input type="checkbox" ng-model="isChecked" ng-change="insertinvited(user.name)">
</li>
</ul>
在我的控制器中:
$scope.invited = [];
$scope.insertinvited= function (name) {
if($scope.isChecked){
$scope.invited.push(name)
} else {
console.log($scope.invited);
}
};
但这不起作用,在控制台中数组总是为空。
But this is not working, in the console the array is always empty.
推荐答案
您的代码中的问题是所有人都使用了您的复选框模型( isChecked
) 用户
您已重新阅读:
The problem in your code is that your checkbox model (isChecked
) is used by all the users
you ngRepeated on:
<ul class="list-group" ng-repeat="user in users">
...
<input type="checkbox" ng-model="isChecked" ng-change="insertinvited(user.name)">
</ul>
我建议您为每个用户设置一个复选框模型:
I suggest you to have a checkbox model for each user:
<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
请注意,在 ng-change
中,我传递了整个用户
对象,而不仅仅是 user.name
(因为我还需要 user.isChecked
property)。
Note that in your ng-change
, I pass the whole user
object, and not only user.name
(because I will also need the user.isChecked
property).
这是新 insertinvited()
function:
Here is the "new" insertinvited()
function:
$scope.insertinvited = function(user) {
if(user.isChecked) {
$scope.invited.push(user.name);
} else {
var toDel = $scope.invited.indexOf(user);
$scope.invited.splice(toDel);
}
}
这篇关于Angularjs:复选框和ng-change的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!