3

I know it is good practice to not use jQuery inside an AngularJS app, but struggling to work out the AngularJS way of doing this:

$scope.clickEvent = function(event) {
    if($(event.target).hasClass('icon-closed')) {
        $(event.target).removeClass('icon-closed')
        $(event.target).addClass('icon-opened')
    } else {
        $(event.target).removeClass('icon-opened')
        $(event.target).addClass('icon-closed')
    }
}

My HTML:

<div class="component-title icon-closed" 
     ng-model="collapsed" 
     ng-click="collapsed=!collapsed;clickEvent($event)">{{component.name}}</div>

The collapsed code is showing/hiding panels, and the div is within an ng-repeat loop, so nothing to do with the clickEvent function.

I was hoping I could get the class names from the event object & alter them without using jQuery. Any ideas?

Thanks :)

1 Answer 1

5

You can use the ngClass directive to achieve this.

<div class="component-title"
     ng-class="{'icon-closed':collapsed,'icon-opened':!collapsed}"
     ng-model="collapsed"
     ng-click="collapsed=!collapsed">{{component.name}}</div>

More information on ngClass can be found here.

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant - works! I did play around with ng-class, but never thought to use my 'collapsed' var with it. Simple really! Thanks a lot :) Still getting my head around AngularJS when I've been using jQuery for so long...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.