[英]Checkbox not working as expected in Angularjs
我有项目列表,并希望为所有这些项目分配复选框。 我已经尝试了下面的代码,但它没有按预期工作。 如果我点击全选; 然后只选择所有正在检查,如果我点击任何其他项目,那么所有项目都将被检查。
<div class="select">
<input type="checkbox" ng-model="selectAll"
ng-init="selectAll=false;" class="filled-in"
id="userprofiles"/>
<label for="userprofiles">Select all</label>
</div>
<ul class="collection">
<li class="collection-item" ng-repeat="profile in userprofiles">
<input ng-model="user.profile"
ng-init="user.profile=false"
class="filled-in" type="checkbox"
id="userprofile"
value="{{profile.profile}}"/>
<label for="userprofile"> {{profile.profile_name}}</label>
</li>
</ul>
Controller.js:
$scope.user.profile = [];
$scope.$watch('selectAll', function(newValue, oldValue) {
angular.forEach($scope.userprofiles, function(selected, item) {
$scope.user.profile[item] = newValue;
});
});
试试吧
angular.module("app", []).controller("profileCtrl", function($scope){ $scope.profiles = [ {value:'Profile 1', selected:true}, {value:'Profile 2', selected:false}, {value:'Profile 3', selected:true}, {value:'Profile 4', selected:false} ]; $scope.toggleAll = function() { var toggleStatus = !$scope.isAllSelected; angular.forEach($scope.profiles, function(profileprofile){ profileprofile.selected = toggleStatus; }); } $scope.profileToggled = function(){ $scope.isAllSelected = $scope.profiles.every(function(profile){ return profile.selected; }) } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> </script> <div ng-app="app" ng-controller="profileCtrl"> <form> <input type="checkbox" ng-click="toggleAll()" ng-model="isAllSelected">Select all <br> <div ng-repeat = "profile in profiles"> <input type="checkbox" ng-model="profile.selected" ng-change="profileToggled()">{{profile.value}} </div> </form> {{profiles}} </div>
问题在于您的ng-repeat:
ng-model="user.profile"
您已为重复中的所有复选框指定了相同的ng-model。 所以我检查/取消选中所有人都会反映出价值。 尝试使用$ index分配ng-model,以便每个复选框都有不同的ng-model。
对于全选 ,您使用两个不同的变量:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.