简体   繁体   English

Angular.js:使用ng-class和click函数更改类

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

I have this array of objects on my controller (self.years) 我的控制器上有这个对象数组(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: 在我的标记中,我使用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: 如果在我的控制器上我已经有一个yearSelected,并且每个按钮都有一个单击功能来更改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? ...我如何使用ng-class将该对应的按钮赋予yearSelected类?

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 在用户界面上,将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 }"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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