Saturday, September 21, 2013

icon approach of checkbox in angularJs

Using icons vs checkbox or  ng-check .
Select boxes are great for forms.

When saving the change to the server on a click...this works too.
The icons are from font awesome.

<div ng-repeat="item in items">
 <i 
    ng-class="{'true':'icon-check','false':'icon-check-empty'}[item.selected]" 
    ng-click="fooClick(item)"></i>
</div>

Explained:  The ng-class has a JavaScript object {...} with an item selector [item.selected].  All this happen inline to paint the proper icon.

The best part is you can see the icon choices in the html and do not have to look in the js files.  For larger lists I would not do it inline.

When user clicks, fooClick is invoked and I change the item in the database and change the var in the item.  Thanks to angularJs binding, the ui is updated.

My Controller code.

Note: I have boolean strings.
Like a good developer, I'm not 'boxing' item.selected by directly assigning it while operating on it. For more info on boxing click here.

$scope.fooClick = function (item) {
  var tf = (item.selected === 'true') ? 'false' : 'true';//watchout... boolean strings
  item.selected = tf;
  saveToDatabase(id,val);
}

1 comment: