Martin Palis
Martin Palis

Reputation: 133

Changing CSS from AngularJS

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.

Upvotes: 8

Views: 8518

Answers (1)

StuR
StuR

Reputation: 12218

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.

Upvotes: 9

Related Questions