Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 518
Martin Palis Avatar asked Apr 17 '13 21:04

Martin Palis


1 Answers

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.

like image 174
StuR Avatar answered Sep 28 '22 06:09

StuR