Using AngularJS ng-click and ng-class
Continuing from the previous tutorial, we now add a “mark done” button next to each of our list items.
1. This was implemented by adding the button element in our HTML …
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…
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 …
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…
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 …
5. And we define the markDone function in our controller (in app.js) as follows.
markDone function in controller
It works just as before.