AngularJS: Set active item in ng-repeat

angularjs set active item

When using sliders or any other multi item control to display content, you often see the class

.active

that indicates which item is currently shown while others wait their turn. This is accomplished by declaring the first items class as active (class=”active”). But how do you declare the active item if you don’t see it in the markup and instead rely on the ng-repeat directive to serve content. You want to use the power of AngularJS to give you fresh content through binding, and still be able to power up sliders with declaring the first item? Easy.

Create your own AngularJS directive that will watch your DOM element and when it is fully rendered appoint the active class to the first element.

Step 1

Create a new file in your project folder.

I called mine “contentslider.js”. Paste in it this code:

 

angular.module('yourApp').directive('contentSlider', function() {

        return function(scope, element) {
            if (scope.$last) {
                element.addClass('active');
            }
        };

    });

 

This code waits for the last element to be rendered after ng-repeat and then gives the element on which it was called the active class.

Be careful to change “yourApp” to whatever your AngularJS app name is.

IMPORTANT: When using AngularJS directives, you have to mind naming them proper. When declaring them you must use camel case, but when calling them in the markup you use dashes -> in directive: contentSlider / in markup: content-slider

You can get more details here: https://docs.angularjs.org/guide/directive

 

Step 2

Add your directive to the markup

 

<div ng-repeat="item in items" content-slider></div>

 

As mentioned earlier, even though we named our directive contentSlider, in markup we call it with dashes between words (AngularJS recognizes words from capital letters).

 

Step 3

Include your directive in index.html

Add a new script tag just before the end of the body tag in your index.html (where all your other AngularJS files are included).

 

<script src="path/to/your/directory/contentslider.js"></script>

 

That’s it. No need for any complex functions or scope.$watch directives. This is really easy and fast to implement.

 

Leave a Reply

Your email address will not be published. Required fields are marked *