Angular.js:用ng-class和点击功能改变class

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

我的控制器上有这个对象数组 (self.years)

    var self = this;

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

在我的标记中,我使用它为使用 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>

如果在我的控制器上我已经有一个 yearSelected 加上每个按钮的点击功能来更改那个 yearSelected:

self.yearSelected = self.years[5];

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

...如何使用 ng-class 将相应的按钮提供给 yearSelected a "selected" class?

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

在 UI 上,将 ng-class="{ 'active': $index === currentIndex }" 添加到您的按钮

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