Reputation: 171
I'm building a project using AngularJS and can't seem to find any example of what I'm looking for...
Using AngularJS, I know how to add a class to anything that's clicked, but how do I add a class to all previous items and remove class from all next items?
I'd like to do the jquery equivalent of .prevAll()/.nextAll(), but using AngularJS.
Here's and example of the jquery way for reference:
HTML:
<a class="btn btn-primary"> Progress 1</a>
<a class="btn btn-primary"> Progress 2</a>
<a class="btn btn-primary"> Progress 3</a>
<a class="btn btn-primary"> Progress 4</a>
<a class="btn btn-primary"> Progress 5</a>
<a class="btn btn-primary"> Progress 6</a>
Jquery:
$(".btn").on("click", function(){
$(this).addClass('active');
$(this).prevAll().addClass('active');
$(this).nextAll().removeClass('active');
});
https://jsfiddle.net/mujaji/yy82twho/1/
I'm trying to figure out how to do using AngularJS. Can someone explain a good strategy or standard?
thanks Joe
Upvotes: 0
Views: 214
Reputation: 1001
As all the <a>
have same structue so i am assuming it is generated by ng-repeat
.
You can do this by using the $index of ng-repeat in angularjs as below
<a class="btn btn-primary" ng-class="{'active': $index <= selectedIndex}"
ng-repeat="p in progress" ng-click="click($index)"> {{p}}</a>
active
class will be automatically added and removed to a tag based on the condition given in ng-class
selectedIndex
is set in the controller based on the <a>
clicked.
In the controller you will have somthing like below.
$scope.progress = ['Progress 1','Progress 2','Progress 3','Progress 4','Progress 5','Progress 6'];
$scope.selectedIndex = 0;
$scope.click = function(indexclicked){
$scope.selectedIndex = indexclicked;
}
Here is the working Jsfiddle demo i have created : http://jsfiddle.net/Makarand_Patil/U3pVM/34638/
Hope this helps you.
Upvotes: 1