选定按钮的ng-class

时间:2018-04-18 15:13:21

标签: angularjs button angularjs-ng-click ng-class

我正在ServiceNow中构建一个小部件,我正在尝试为选定的按钮添加一些CSS样式。在网上挖掘之后,我认为我已经完成了基本结构,但是对于如何确保选择按钮然后相应地设置样式仍然有点困惑。

以下是我的HTML的样子:

<div class="chiclets">
   <button class="btn btn-slots" ng-class="{'btn-selected':selectedSlot.apptTime == slot.apptTime }" ng-click="selectedSlot = time" ng-repeat="time in c.availTime">{{time.apptTime}}</button>
</div>

这会从我的c.availTime对象数组中生成一组可用时隙: enter image description here

对象数组的客户端脚本如下所示:

$scope.getTimeSlots = function(date, place) {
        date = moment(date).format("YYYY-MM-DD")
        //every time a date is chosen, first clear time array
        c.availTime = [];
        for(var a=0; a<c.data.avail.length; a++){
            if(date == c.data.avail[a].start_date && place == c.data.avail[a].appointment_location) {               

                c.availTime.push({
                    apptTime:c.data.avail[a].start_time,
                    availability: c.data.avail[a].availability
                });
            }
        }
};

我的问题是,如果用户点击上午9点的时间段,我的ng-click是否正确捕获了该时间。如果是这样,我如何格式化我的ng-class,以便btn选择的类具有红色背景(例如)。

谢谢!

2 个答案:

答案 0 :(得分:1)

您的考试是selectedSlot.apptTime == slot.apptTime

不应该是selectedSlot.apptTime == time.apptTime吗?

因为我没有看到slot变量。

我猜测试甚至可能是selectedSlot == time(同一参考)。

答案 1 :(得分:0)

Create one more property isSelected = false and set it as true on ng-click and apply class if isSelected property is true.

See code below

css

<style>
.btn-selected {backgraound-color:red}
</style>

html

<div class="chiclets">
 <button class="btn btn-slots" ng-class="{'btn-selected':time.isSelected == true }" ng-click="btnClick($index)" ng-repeat="time in c.availTime">{{time.apptTime}}</button>
</div>

Js

$scope.getTimeSlots = function(date, place) {
    date = moment(date).format("YYYY-MM-DD")
    //every time a date is chosen, first clear time array
    c.availTime = [];
    for(var a=0; a<c.data.avail.length; a++){
        if(date == c.data.avail[a].start_date && place == c.data.avail[a].appointment_location) {               

            c.availTime.push({
                apptTime:c.data.avail[a].start_time,
                availability: c.data.avail[a].availability,
                 isSelected : false
            });
        }
    }
};
 $scope.btnClick  = function(index) {
     angular.foreach( c.availTime,function(v,k){
       if(k == index){
         v.isSelected  = true;
       } else {
         v.isSelected  = false;
       }
})
}