简体   繁体   中英

Angular.js: change a class with ng-class and a click function

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?

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

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 }"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM