Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add the `active` class on click of `li` element

I am quite new to AngularJS. I need to know how to handle this scenario using it.

I have an array with values. I am using ng-repeat to iterate the array and it works fine. My requirement is how to add a class(active) to first child of ul and whenever user clicks, the clicked element should get the active class and remove the active class from the rest of the li elements.

I've done that in JQuery very easily like:

$('li').addClass('active').siblings().removeClass('active')

But how to achieve the same here?

My code :

JavaScript Controller

var myApp = angular.module("myApp", []);

myApp.controller("main", function ($scope) {

  $scope.items = [1,2,3,4,5];

  $scope.activate = function (item) {

    //how to active this item?

    //onload how to add class on first li?

  }

})

HTML

 <ul>

    <li ng-click="activate(item)" ng-repeat="item in items">
        {{item}}
    </li>

  </ul>

Live Demo

like image 582
3gwebtrain Avatar asked Jul 08 '15 08:07

3gwebtrain


1 Answers

How about this. Store the current active item in your controller and apply a class to it if it is the one.

HTML

<ul>
    <li 
        ng-click="activate(item)" 
        ng-repeat="item in items"
        ng-class="{'active': item == active}">{{item}}
    </li>
</ul>

JS Controller

$scope.items = [1,2,3,4,5];
$scope.active = items[0]; // for onload first element active
$scope.activate = function (item) {
    $scope.active = item;
}

Plunker

like image 68
SDekov Avatar answered Sep 18 '22 17:09

SDekov