0

Goal: I want to display the content of a div based on checkboxes' status but also want to have these div visible by default

Assuming I have the following piece of code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>
</head>
<body ng-app>
<label>red <input type="checkbox"  ng-model="red"  /></label><br />
<label>blue <input type="checkbox"  ng-model="blue"   /></label><br />
<div ng-show="red" style="width: 50px; height: 50px; background-color: red;"></div><br />
<div ng-show="blue" style="width: 50px; height: 50px; background-color: blue;"></div><br />
<div ng-show="red" style="width: 50px; height: 50px; background-color: red;"></div><br />
</body>
</html>

With this code, my 2 checkboxes are not checked by default, and each div is correctly displayed whenever I check one of the two checkboxes

Now I tried to append:

ng-checked='true'

By default my checkboxes are now selected but the div are still not displayed. I tried to poke around with some ng-init, ng-hide or ng-load but my experience with Angular is really limited.

Anyone can point me to a direction?

PERPO
  • 3,812
  • 1
  • 13
  • 20

2 Answers2

1

ng-checked is not intended to be used with ng-model

If you want to change a checkbox change it's model value:

$scope.red=true;

Also note that you should always use an object in ng-model or you will forever run into problems with binding due to child scopes

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

ng-init seems to work.

<label>red <input type="checkbox"  ng-model="red" ng-init="red=true" /></label><br />

fiddle: http://jsfiddle.net/bn8bn3nc/

See this S.O. question: Angular js init ng-model from default values

Community
  • 1
  • 1
Steve
  • 1,326
  • 14
  • 21
  • 1
    but also read the docs for `ng-init` and will see that it is not intended for this purpose and not recommended either – charlietfl Sep 21 '15 at 23:31
  • Thanks - Works great. – PERPO Sep 21 '15 at 23:34
  • @charlietfl True. The fist answer for the Q I linked started with "This is a common mistake in new Angular applications. You don't want to write your values into your HTML on the server if you can avoid it. If fact, if you can get away from having your server render HTML entirely, all the better." – Steve Sep 21 '15 at 23:35
  • in early days of angular it was a common practice. Not sure where it can cause problems, but they added the disclimaer in docs after it matured some – charlietfl Sep 21 '15 at 23:38