Reputation: 1337
I am trying to change the color of the specific heading in AngularJS. My issue is that there are multiple headings with the same class in it and I would like to change the color of the one that is clicked only. Currently, I have tried:
HTML:
<div class="row">
<div class="span6">
<div class="heading">Heading 1</div>
</div>
<div class="span1">
<i class="pull-right" expand="check" collapse="close"></i>
</div>
</div>
JS:
scope.setExpandCollapse = function () {
if (scope.expand && scope.collapse) {
if (isOpen) {
angular.element(document.querySelectorAll('.heading')).removeClass('color-change');
} else {
angular.element(document.querySelectorAll('.heading')).addClass('color-change');
}
}
};
The issue is that it changes color of all the headings due to querySelectorAll
. Is there a way for me to do this without changing my HTML?
Upvotes: 0
Views: 247
Reputation: 5729
There's many ways to solve this. Here's one:
If you trigger the click that toggles the expanded/collapsed view using ngClick
directive, you'll have access to the $event
of that click action. If you have the event, you can simply reference $event.target
(origin of the click) and toggle class directly on it.
In template:
<h1 class="heading" ng-click="$ctrl.toggle($event);">
Heading
</h1>
In controller:
this.toggle = function($event) {
$event.preventDefault();
angular.element($event.target).toggleClass('color-change');
};
Edit: if you're attaching a click handler on certain elements, it's useful to add $event.preventDefault();
to prevent any default actions that would be attached to such elements (i.e. button submitting a form). Since you probably don't want to remember which elements might do something nasty, it's safest to always have preventDefault()
on your events, unless you explicitly want to allow the default action to take place.
Upvotes: 1
Reputation: 567
For this you'll have to create a directive as in AngularJS you are not "allowed" to touch the DOM outside them.
JS
yourAngularApp.directive('changeColor', function(){
return {
restrict : "A",
link: function(scope, element, attributes) {
elem.bind('click', function() {
element[0].classList.toggle('color-change');
});
}
};
});
HTML
<div class="row">
<div class="span6">
<div class="heading" change-color>Heading 1</div>
</div>
<div class="span1">
<i class="pull-right" expand="check" collapse="close"></i>
</div>
</div>
The previous code is aware of a click on the element where the directive is applied and toggles (adds or removes) the class 'color-change' on click.
Upvotes: 0