在Angular.js动态类 [英] Dynamic class in Angular.js

查看:89
本文介绍了在Angular.js动态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个CSS类动态添加到<立GT; 元素,我遍历。
循环是这样的:

I want to dynamically add a css class to an <li> element I am looping over. The loop is like this:

<li ng-repeat="todo in todos" ng-class="{{todo.priority}}">
  <a href="#/todos/{{todo.id}}">{{todo.title}}</a>
  <p>{{todo.description}}</p>
</li>

在我的待办事项模式,我有物业的优先级可以是紧急,不那么重要或正常的,我只是想分配类每个元素。

In my todo model, I have the property priority which can be "urgent", "not-so-important" or "normal" and I just want to assign the class for each element.

我知道我可以像纳克级的布尔做={'急':todo.urgent}
但我的变量不是一个布尔值,但有三个值。
我会怎么做呢?
还要注意的是,我不希望使用 NG-风格=...因为我的班会改变一些视觉的东西。

I know I can do this for a boolean with something like ng-class="{'urgent': todo.urgent}" But my variable is not a boolean, but has three values. How would I do this? Note also that I do not want to use ng-style="..." since my class will alter several visual things.

推荐答案

您可以简单地指定一个函数作为前pression,并从那里返回正确的类。
修改:也有动态的类更好的解决方案。请参见下面的注释。

You can simply assign a function as an expression and return proper class from there. there is also better solution for dynamic classes. Please see note below.

从片段视图:

&LT; D​​IV纳克级=appliedClass(MyObj中)&GT; ...&LT; / DIV&GT;

和在控制器:

$scope.appliedClass = function(myObj) {
    if (myObj.someValue === "highPriority") {
        return "special-css-class";
    } else {
        return "default-class"; // Or even "", which won't add any additional classes to the element
    }
}

做得更好方式本

我最近了解了另一种方法。您传递其具有对应于你操作的类属性的对象,而值是前pressions或布尔变量。一个简单的例子:

Better way of doing this

I've recently learned about another approach. You pass in an object which has properties corresponding to the classes you operate on, and the values are expressions or boolean variables. A simple example:

纳克级={活跃:user.id == activeId}

在这种情况下,有效类只要将添加到元素为 user.id 匹配 activeId $范围对象>!

In this case active class will be added to the element as long as user.id matches activeId from the $scope object!

这篇关于在Angular.js动态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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