从 AngularJS 更改 CSS [英] Changing CSS from AngularJS

查看:20
本文介绍了从 AngularJS 更改 CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 angularjs 控制器更改 DOM 不是一个好习惯.在我的应用程序中,单击链接后,我正在更改 ngView 中的 html 元素的类.预期的行为是,我有三个 div,如果中间一个显示与否,我正在更改.我正在从控制器执行此操作.我读过,应该在指令中完成 DOM 操作,但我的想法不够广泛,无法找到解决方案.拜托了,如果你有什么建议,我会很高兴的.

解决方案

使用 ng-class.

例如:

http://jsfiddle.net/rd13/eTTZj/75/

app = angular.module('myApp', []);app.directive("点击", function () {返回函数(范围,元素,属性){element.bind("点击", function() {scope.boolChangeClass = !scope.boolChangeClass;范围.$应用();});};});

一些 HTML:

<div>一个</div><div ng-class="{'my-class':boolChangeClass}">两个</div><div>三</div><点击按钮>点击我</button>

当您单击按钮时,中心 div 的类将根据您范围内设置的 boolen 值而变化.

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.

解决方案

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.

这篇关于从 AngularJS 更改 CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆