Javascript “角度JS”复选框不起作用
我从两小时前就开始头疼。因为我是新来的 我有下面的复选框,我希望将复选框值推送到数组中。如果我取消选中,它将从数组中弹出。我尝试了以下代码。但是不工作Javascript “角度JS”复选框不起作用,javascript,angularjs,checkbox,Javascript,Angularjs,Checkbox,我从两小时前就开始头疼。因为我是新来的 我有下面的复选框,我希望将复选框值推送到数组中。如果我取消选中,它将从数组中弹出。我尝试了以下代码。但是不工作 <label ng-repeat="r in MessageUserList"> <input type="checkbox" name="selectList[]" value="{{r}}" ng-checked="selection.indexOf(r) > -1" ng-click="tog
<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>
在我的控制器中:
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)中,使用如下内容: //html
<label>Check me to check both: <input type="checkbox" ng-model="ch" ng-changed="saveChange()"></label>
<br/>
{{ch}}
试试这个
var-app=angular.module('myApp',[]);
应用程序控制器('surveyController',功能($scope){
$scope.MessageUserList=[{
“成员”:{
“成员id”:8,
“名字”:“大卫先生”,
“姓氏”:“Raz”,
“电话”:122,
“密码”:“dd”,
“邮件”:sushil@asd.com",
“系统日期”:“2017年5月18日下午3:26:01”,
“社会id”:1,
},
“单位分配”:“N”
}];
$scope.selection=[];
//按名称切换给定r的选择
$scope.toggleSelection=函数toggleSelection(r){
var idx=$scope.selection.indexOf(r);//此处的错误indexOf(r)
//当前已选定
如果(idx>-1){
警报(“相同检查”);
$scope.selection.splice(idx,1);
}
//是新选中的
否则{
警报(“新检查”);
$scope.selection.push(r);
警报(JSON.stringify($scope.selection));
}
}
});
{{r.member.first_name}
您的$scope.selection是否在控制器中或代码中的其他地方实例化?更改var selection=[]代码>到$scope.selection=[]代码>可能有帮助。:)@Radouane I刚刚声明为var selection=[];。正如@Pengyy提到的,您必须在$scope内声明它。请参阅Pengyy注释。是的,我使用$scope声明..我更改了var selection=[]代码>到$scope.selection=[]代码>并在警报中进行了相同的更改:)
<label>Check me to check both: <input type="checkbox" ng-model="ch" ng-changed="saveChange()"></label>
<br/>
{{ch}}
.controller('yourCtrl', function($scope){
$scope.ch = false;
$scope.selection=[];
$scope.saveChange = ()=>{
$scope.selection.push(ch);
}
})