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

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

问题描述

我想动态地将一个 css 类添加到我正在循环的 <li> 元素中.循环是这样的:

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.

我知道我可以使用类似 ng-class="{'urgent': todo.urgent}" 的布尔值来执行此操作但是我的变量不是布尔值,而是具有三个值.我该怎么做?另请注意,我不想使用 ng-style="..." 因为我的课程会改变一些视觉效果.

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.

推荐答案

您可以简单地将函数分配为表达式并从那里返回正确的类.动态类也有更好的解决方案.请参阅下面的说明.

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.

视图片段:

<div ng-class="appliedClass(myObj)">...</div>

在控制器中:

$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
    }
}

更好的方法

我最近了解了另一种方法.您传入一个对象,该对象具有与您操作的类相对应的属性,其值是表达式或布尔变量.一个简单的例子:

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:

ng-class="{ active: user.id == activeId }"

在这种情况下,只要 user.id$scope 中的 activeId 匹配,active 类就会被添加到元素中 对象!

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天全站免登陆