0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

$scope.context = {accounts : :[]}; Here accounts is $scope.accounts right ?
yes but it's on purpose, as said in my last sentece, this avoid scope problem, your code might not working if you use some directive between the controller declaration and the ng-repeat. There are recurrent case here because of ngIf.
0

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.