gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:20:46 24 4
gpt4 key购买 nike

我的 Controller 上有这个对象数组(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>

如果我的 Controller 上已经有一个yearSelected,并且每个按钮都有一个单击功能来更改该yearSelected:

self.yearSelected = self.years[5];

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

...我如何使用 ng-class 为 YearSelected 提供相应的按钮“选定”类?

最佳答案

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

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

关于javascript - Angular.js : change a class with ng-class and a click function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38662334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com