简体   繁体   中英

Checkbox is not working properly with ng-repeat, AngularJs

I want to make multiselect checkbox using ng-repeat. It is working fine if I don't have pre-selected checkbox. But when I have preselected checkbox then its behaviour is totally unusual.

<div ng-repeat="account in accounts">
    <input ng-model="selectedAccounts[account.id]"              
    ng-checked="{{account.lastchecked}}" type="checkbox">       
</div>

In Controller I got selected id as:

$scope.selectedAccounts = [];
angular.forEach($scope.selectedAccounts, function(value, key) {
    if(value == true) {
        selectedIds.push(key);
    }
}); 

The problem here is that I have to initialise selectedAccounts with initial array. If I don't do this then it gives me undefined. When I have 'lastchecked' true for some accounts then it shows pre-checked values according to lastchecked but when I try to retreive $scope.selectedAccounts it give me empty array. But when I manually check/uncheck each option then $scope.selectedAccounts give me correct result.

Here is how i would do it :

$scope.context = {accounts : :[]};// init is important to place the variable in that scope on not in a child
<div ng-repeat="account in context.accounts">
    <input ng-model="account.lastchecked" ng-checked="account.lastchecked"              
       ng-true-value="true" ng-false-value="false" type="checkbox">       
</div>

Ng-true-value and ng-false-value ensure that the value will be the boolean true/false instead of strings.

After to get the selectedAccount you just search.filter account with lastchecked==true

The indermediary object context is to avoid scope issues, scope inheritance fails on simple fields. This is a limit of javascript. In angularJS this is called DOT notation.

Go through this

 var jimApp = angular.module("mainApp", []); jimApp.controller('mainCtrl', function($scope){ $scope.selectedAccounts = {"3":true}; $scope.accounts = [{id:1, name:"account1", checked: true}, {id:2, name:"account2"}, {id:3, name:"account3"}] }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="mainApp" ng-controller="mainCtrl"> <div ng-repeat="account in accounts"> <input ng-model="selectedAccounts[account.id]" ng-checked="selectedAccounts[account.id]" type="checkbox">{{account.name}} </div> <div>{{selectedAccounts}}</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM