Monday, December 31, 2012

AngularJS checkbox initialization

With ng-checked=true, though the checkbox's state is checked, the model is not synched with the checkbox's state on initial page load, i.e. Love won't appear and isImportant won't appear on UI:

<p>Show important: <input ng-model='isImportant' type='checkbox' ng-checked='true'/></p>

<p ng-show='isImportant'>Love</p>


Value initialization should be done on ng-init:

<p>Show important: <input ng-model='isImportant' type='checkbox' ng-init='isImportant=true'/></p>

<p ng-show='isImportant'>Love</p>


Love will appear, and true would appear too.

Better yet, initialize models on controller:

<p>Show important: <input ng-model='isImportant' type='checkbox'/></p>

<p ng-show='isImportant'>Love</p>


function SomeController($scope) {
    $scope.isImportant = true;        

That left us with a lingering question, if model initialization would suffice on ng-init and it's ideal to set them on controller, when to use ng-checked then? For the life of me I can't find it in google, and I find ng-checked anathema to AngularJS' single-source-of-truth principle; and in order to facilitate single-source-of-truth principle, two-way binding should work all the time, but in ng-checked case I don't know why it doesn't sync its state to the model.

I'm still finding a use case for ng-checked ツ

No comments:

Post a Comment