两个小时让我头疼。因为我是 Angular JS 的新手。
我有以下复选框,我希望将选中的复选框值推送到数组中。如果我取消选中它应该从数组中弹出。我尝试了以下代码。但不工作...
<label ng-repeat="r in MessageUserList">
<input type="checkbox" name="selectList[]" value="{{r}}"
ng-checked="selection.indexOf(r) > -1" ng-click="toggleSelection(r)">
{{r.member.first_name}}</label>
来自 Web 服务的 MessageUserList JSON 如下:
{
"member":{
"member_id":8,
"first_name":"Mr. David",
"last_name":"Raz",
"phone":122,
"password":"dd",
"mail":"sushil@asd.com",
"system_date":"May 18, 2017 3:26:01 PM",
"society_id":1,
},
"flat_assign":"N"
}
在我的 Controller 中:
var selection=[];
// Toggle selection for a given r by name
$scope.toggleSelection = function toggleSelection(r) {
var idx = $scope.selection.indexOf(r); //Error here indexOf(r)
// Is currently selected
if (idx > -1) {
alert("Same checked");
$scope.selection.splice(idx, 1);
}
// Is newly selected
else {
alert("New checked");
$scope.selection.push(r);
alert(JSON.stringify(selection));
}
}
出现错误: 类型错误:无法读取未定义的属性“indexOf” 在 b.toggleSelection (controllers.js:129)
最佳答案
试试这个,
<!DOCTYPE html>
<html>
<head>
<script Src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('surveyController', function($scope){
$scope.MessageUserList = [{
"member":{
"member_id":8,
"first_name":"Mr. David",
"last_name":"Raz",
"phone":122,
"password":"dd",
"mail":"sushil@asd.com",
"system_date":"May 18, 2017 3:26:01 PM",
"society_id":1,
},
"flat_assign":"N"
}];
$scope.selection = [];
// Toggle selection for a given r by name
$scope.toggleSelection = function toggleSelection(r) {
var idx = $scope.selection.indexOf(r); //Error here indexOf(r)
// Is currently selected
if (idx > -1) {
alert("Same checked");
$scope.selection.splice(idx, 1);
}
// Is newly selected
else {
alert("New checked");
$scope.selection.push(r);
alert(JSON.stringify($scope.selection));
}
}
});
</script>
</head>
<body ng-controller="surveyController" ng-app="myApp">
<label ng-repeat="r in MessageUserList">
<input type="checkbox" name="selectList[]" value="{{r}}"
ng-checked="selection.indexOf(r) > -1" ng-click="toggleSelection(r)">
{{r.member.first_name}}</label>
</body>
</html>
关于javascript - Angular JS 复选框不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44129596/