AngularJS way of changing class name on ng-click
-
21-12-2019 - |
Question
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 :)
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow