8

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.

1 Answer 1

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.

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

3 Comments

Thank you! So not a lot of refactoring is needed :)
@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...
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?

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.