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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With