Prabin Upreti
Prabin Upreti

Reputation: 498

How to select element by classname and iterate through those objects in angularJs?

I am new to angularJs, i have a function in my angular controller as

$scope.addPrimaryClass = function () {
        var weekDayBtn = $(".weekdayButton");
        weekDayBtn.addClass("btn-white").removeClass("btn-primary");
        $.each(weekDayBtn,function (index) {
            if($(this).val()==$scope.weekly){
                $(this).addClass("btn-primary").removeClass("btn-white");
            }
        })
    };

In view i have :

<div class="btn-group">
                        <button class="btn btn-white weekdayButton" type="button" value="7" ng-click="weekdayClicked($event);">Sun</button>
                        <button class="btn btn-white weekdayButton" type="button" value="1" ng-click="weekdayClicked($event);">Mon</button>
                        <button class="btn btn-primary weekdayButton" type="button" value="2" ng-click="weekdayClicked($event);">Tue</button>
                        <button class="btn btn-white weekdayButton" type="button" value="3" ng-click="weekdayClicked($event);">Wed</button>
                        <button class="btn btn-white weekdayButton" type="button" value="4" ng-click="weekdayClicked($event);">Thu</button>
                        <button class="btn btn-white weekdayButton" type="button" value="5" ng-click="weekdayClicked($event);">Fri</button>
                        <button class="btn btn-white weekdayButton" type="button" value="6" ng-click="weekdayClicked($event);">Sat</button>
                    </div>

The code in addPrimaryClass works as required in console since i can use normal jquery there, but the code doesn't work in angular itself. Basically, i want to change the css of buttons according to one of the scope value. Please help!!!

Upvotes: 0

Views: 173

Answers (1)

o--oOoOoO--o
o--oOoOoO--o

Reputation: 770

You can use the ng-class directive to apply the classes depending on what the scope variable is. For example:

<button class="btn weekdayButton" type="button" value="7" ng-click="weekdayClicked($event);" ng-class="($(this).val()==$scope.weekly) ? 'btn-primary' : 'btn-white'">Sun</button>

There are several ways using the ng-class directive. Please have a look at the documentation and decide what's best for you: https://docs.angularjs.org/api/ng/directive/ngClass


On a separate note, you might want to remove all jQuery from your Angular code :)

Upvotes: 1

Related Questions