0

I have this array of objects on my controller (self.years)

    var self = this;

    self.years =[
        {"year":"2010"},
        {"year":"2011"},
        {"year":"2012"},
        {"year":"2013"},
        {"year":"2014"},
        {"year":"2015"}
    ];

In my markup I'm using that to make a button for each object using ng-repeat:

         <div class="btn-container col-md-2" ng-repeat="year in ctrl.years">
            <button class='btn year-btn' year="{{$index}}" ng-click="ctrl.updateYear($index)">{{year.year}}</button>
         </div>

If on my controller I have a yearSelected already plus a click function for each button to change that yearSelected:

self.yearSelected = self.years[5];

self.updateYear = function(indexSelected) {
    self.yearSelected = self.years[indexSelected];
};

...how do I give that corresponding button to yearSelected a "selected" class using ng-class?

2
  • You could do ng-class="{selected: self.yearSelected === year.year }" Commented Jul 29, 2016 at 15:25
  • Pankaj's answer works as well assuming you don't have repeating values in you array at any point. Otherwise, you would get multiple highlighted buttons. If you have repeating years ever, you'd need to track by $index which you should probably do anyway. Commented Jul 29, 2016 at 15:27

2 Answers 2

2
self.updateYear = function(indexSelected) {
    self.currentIndex = indexSelected; // add this
    self.yearSelected = self.years[indexSelected];
};

On the UI, add ng-class="{ 'active': $index === currentIndex }" to your button

Sign up to request clarification or add additional context in comments.

Comments

0
self.yearSelected = self.years[0];

self.updateYear = function(year) {
    self.yearSelected = year;
};


<div class="btn-container col-md-2" ng-repeat="obj in ctrl.years">
    <button class='btn year-btn' ng-click="ctrl.updateYear(obj)">{{obj.year}}</button>
</div>

//use ng-class="{active: self.yearSelected === obj.year }"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.