从2个小时开始我的头。因为我是角度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>
MessageUserList JSON从Web服务转发为:
{
"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"
}
在我的控制器中:
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));
}
}
收到错误: TypeError:无法读取未定义的属性'indexOf' 在b.toggleSelection(controllers.js:129)
答案 0 :(得分:1)
试试这个,
<!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>
答案 1 :(得分:0)
使用类似的东西:
// HTML
<label>Check me to check both: <input type="checkbox" ng-model="ch" ng-changed="saveChange()"></label>
<br/>
{{ch}}
// JS
.controller('yourCtrl', function($scope){
$scope.ch = false;
$scope.selection=[];
$scope.saveChange = ()=>{
$scope.selection.push(ch);
}
})