Insert conditional css class in AngularJs (Mini-challenge 7) Answer

Table of Content

Check out Mini-challenge 7 Instructions

Answer:Insert conditional css class in AngularJs (Mini-challenge 7) Answer


In this case you have an array of object that is rendered in a ul with an li for each element and a property on the controller called selectedIndex.
In this scenario we have to Insert conditional css class in the htmls view.

Insert conditional css class

Using the ng-class directive should be the answer.
The simplest way to implement conditional css class in angular is using the object notation within the ng-class directive.

<li ng-class="{green: $index==selectedIndex}">

With this object notation ({green: $index==selectedIndex}), we can put a condition on where we want to apply the css class. In this specific case we are using the $index build-in variable for ng-repeat, like this.

<div ng-controller="Ctrl">  
    <li ng-class="{green: $index==selectedIndex}" ng-repeat="item in list"> <!--apply "green" class to the 3er element -->

Here is the ng-class official documentation:

See working codde below:

If you have a solution for this challenge, different from the proposed solution on this post, don't be shy and share it with us ­čÖé