javascriptangularjs

Checkbox selection is lost when using ng-init


I want to initialize(check) my checkbox once based on some value.Hence i am using ng-init but problem is when i load another template and come back to that previous template again i think ng-init gets call and i loose those new checkbox selection.

Code :

$scope.lst = [
{item:'banana', selected:true},
{item: 'apple', selected:false},
{item:'milk', selected:false},
{item: 'tomato', selected:false},
{item:'juice', selected:false}
]
});
<div ng-repeat="item in lst">
     <input ng-model="item.parentSelected" ng-init="item.parentSelected=item.selected" type="checkbox">
</div>

So by default i would like to display banana as selected but problem is when user select apple and milk and i load another template and user comes back to same page(again i load first template) so i guess ng-init gets call again and i loose my apple and milk selection.

when i remove ng-init then i have apple and milk selection.

Update: I guess the problem is with ng-init only as because ng-model is binded with parentSelected and for apple and milk i have selected as false so when i select apple and milk and i load another template and again i load previous template ng-init is making selection of only banana because of ng init="item.parentSelected=item.selected"

How to make default selection of apple and preserve other selection when my templates gets load??


Solution

  • It gets lost because when you open again that view, the controller gets init again, and the previous selection gets lost because the view is init again from zero.

    Define a service where to store your selection, inject it in your controller and store inside the service the selected value. Then define a function inside your controller called from the ng-init. Inside this function check if a value has been stored: if so, assign the value to the stored one, otherwise pre-select the first entry.