davidivad davidivad - 1 year ago 103
Ajax Question

AngularJS, activate checkboxes before ng-model is declared

I'm developing a web application using Angular and I need some checkboxes that are related to the contents of a db so I'm using ng-repeat for that. I want an auxiliary array to control the ng-model and initially all checkboxes must be true.

I get the data from an ajax request and I don't now in advance how many elements I'm going to get so I don't know how many checkboxes will be. The problem is that I don't know the size of the auxiliary array until the ajax call has finished and by that time the checkboxes have already appeared on the screen unchecked.

My code is the following:

<div class="checkbox" ng-repeat="c in categories">
<label for="{{c.id}}" ><input type="checkbox" ng-model="catselection[c.id]">{{c.name}}</label>

And in the controller I have this:

.success(function(data, status, headers, config){
$scope.categories = data;
$scope.catselection = [];
for(x in $scope.categories){
.error(function (data, status, headers, config) {});

The rest of the behavior is correct but I need the checkboxes to be activated at the beginning, I've tried the html attribute checked and even ng-checked and I know is not recommended with ng-model and nothing seems to work so far.

Answer Source

Have you tried ng-init?

<label for="{{c.id}}" ><input type="checkbox" ng-model="catselection[c.id]" ng-init="catselection[c.id] = true">{{c.name}}</label>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download