Look in a different angle using Angular.js


Angular.js is a Superheroic JavaScript MVW Framework which really started drawing my attention recently. So I decided to give it a shot.

3 years ago, I wrote a blog post on jQuery to select grouped checkboxes and it took only a single line of code to achieve that. But we can achieve the same result without writing a single line of Javascript code. The reason for that is Angular.js allows to do two way data binding so in this case I’ve bound child checkboxes with the parent one by using a special angular directive ng-model and observing the states of checkboxes using ng-checked directive

<div ng-app>
  <div>
    <input ng-model="parent" ng-checked="child_1 && child_2 && child_3 && child_4 && child_5" ng-model="parent"  type="checkbox"/> Select All<br/>
    <input ng-model="child_1" ng-checked="parent" type="checkbox"/> First<br/>
    <input ng-model="child_2" ng-checked="parent" type="checkbox"/> Second<br/>
    <input ng-model="child_3" ng-checked="parent" type="checkbox"/> Three<br/>
    <input ng-model="child_4" ng-checked="parent" type="checkbox"/> Four<br/>
    <input ng-model="child_5" ng-checked="parent" type="checkbox"/> Five<br/>
  </div>
</div>​

ng-app directive tells angular to bootstrap the application, without such directive other directives will not work and simply be ignored.

Demo: http://jsfiddle.net/codef0rmer/4Mpq7/

Angular.js is really fascinating me and you can learn more about it on Angular.js Tutorial

Advertisements

2 thoughts on “Look in a different angle using Angular.js

  1. There’s a bug in this,

    Steps:
    1. Start checking each child one by one, (First…second…and so on) which would enable the parent (Select All)
    2. Select the parent, and un-select it
    3. Now start selecting each child node again, one by one, the parent is no longer selected…

    😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s