Using AngularJS ng-click and ng-class

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Continuing from the previous tutorial, we now add a “mark done” button next to each of our list items.

adding the mark done button

adding the mark done button

1. This was implemented by adding the button element in our HTML …

add button with ng-click

add button with ng-click

Note that we added the AngularJS directive ng-click to the button element.  When the button is clicked, it will execute the statement setting stuff.completed property to true.

2.  When our list item is marked as completed, we want to show a strikeout line across our item.  We do this via the CSS class “strikeItem” with text-decoration of line-through as shown…

define CSS class

define CSS class

3. We want to apply this class to the “li” of any list item that has completed property set to true.  We can do this ng-class directive …

using ng-class

using ng-class

We set the value of this directive to an object (hence the curly braces).  The key of the object is the class name (here “strikeItem”) and the value of the object is the expression (here “stuff.completed”).   When the expression evaluates to true, the class (here “strikeItem”) is applied to the element.

Note that if your class name contains a dash, you need to put your class name in quotes as in …

ng-class=”{‘strikeItem’ : stuff.completed}”

The result is that we have a shopping list with ability to cross off items…

shopping list with completed items

shopping list with completed items

4.  In cases where the ng-click logic is complex, you would rather call a function in ng-click rather than performing everything in the expression.   So we would do the following to call a function named markDone, passing in the object (here it is stuff) that is to be marked done …

calling controller function in ng-click

calling controller function in ng-click

5.  And we define the markDone function in our controller (in app.js) as follows.

defining the controller function

defining the controller function

 

markDone function in controller

It works just as before.