conditional css class AngularJs (Mini-challenge 7)

conditional css class AngularJs Mini-Challenge 7

conditional css class AngularJsAngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The Challenge:

For this challenge we have an object array that is rendered in a ul with an li for each element, also we have a property on the controller called selectedIndex. What would be the best way to add a css class to the li if the index of the array is equal to selectedIndex in AngularJS?

View:
The challenge here is to find the best approach to insert conditional css class AngularJs. This is how the view code looks like, the challenge for you is to find a solution

<div ng-controller="Ctrl">
<ul>
<li class="green" ng-repeat="item in list"> <!--apply "green" class to the 3er element -->
       {{item.name}}
    </li>
</ul>
</div>

Controller:
In the controller we have an array of objects that we are going to render using the ng-repeat on the view. Also we want render the 3rd element with a custom class defined in the

  • html element. We omitted the controller definition in this code example, you can find a more completed doe in the jsfiddle we provided below.
    function Ctrl($scope) {
        $scope.list = [
            {"name": "Item 1", "disposition": "true"},
            {"name": "Item 2", "disposition": "false"},
            {"name": "Item 3", "disposition": "true"},
            {"name": "Item 4", "disposition": "false"},
            {"name": "Item 5", "disposition": "true"}
        ];
    $scope.selectedItem = 3;
    }
    

    See jsfiddle: https://jsfiddle.net/fmdhgho9/4/

    Here you can find a possible solution

    If you feel that the solution is poor or incomplete or there is room for improvement, please share with every one, you can leave a comment.