DOM changes from angularjs controllers are not a good practice. In my application, after clicking on a link, I am changing class of an html element inside ngView. the intended behaviour is, that i have three divs, and I am changing if the middle one is shown or not. I am doing this from a controller. I have read, that doing DOM manipulation should be done in a directive, but my mind is not broad enough to find a solution. Please, if you have a suggestion, I will be glad.
Asked
Active
Viewed 8,513 times
1 Answers
9
Use ng-class.
e.g:
http://jsfiddle.net/rd13/eTTZj/75/
app = angular.module('myApp', []);
app.directive("click", function () {
return function(scope, element, attrs) {
element.bind("click", function() {
scope.boolChangeClass = !scope.boolChangeClass;
scope.$apply();
});
};
});
Some HTML:
<div id="page">
<div>One</div>
<div ng-class="{'my-class':boolChangeClass}">Two</div>
<div>Three</div>
<button click>Click me</button>
</div>
When you click the button, the class of the center div will change depending on the boolen value set within your scope.

StuR
- 12,042
- 9
- 45
- 66
-
Thank you! So not a lot of refactoring is needed :) – Martin Palis Apr 18 '13 at 07:10
-
1@MartinPalis this answer is partially correct. You should be using ng-class.. But instead of a custom click directive you should be using ng-click... – ganaraj Apr 25 '13 at 21:10
-
In the end, I am not so sure. Why to use ng-click instead of custom click directive? Assuming that I want to pack my directive and let it be used as-is, without any need to put callback functions somewhere to my code, isn't the cusom click directive a better solution? – Martin Palis Apr 26 '13 at 11:39