AngularJS |使用ng-class的条件类 [英] AngularJS | Conditional Class using ng-class

查看:116
本文介绍了AngularJS |使用ng-class的条件类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将条件类应用于页面上的元素.

I'm wanting to apply a conditional class to an element on the page.

当前,它正在使用以下代码:

Currently it's working with the following code:

ng-class="{ 'vfnz-form--error' : loginForm.username.$invalid  }

如果输入字段无效,这将应用无效的类.我想在用户输入字段有效时应用"有效" 类.

This applies a invalid class if the input field is invalid. I'm wanting to apply a "valid" class when the user input field is valid.

是否可以在同一行代码中实现?

Is this possible to achieve in the same line of code?

以下是一个小提琴示例: JSFIDDLE

Here is a fiddle example: JSFIDDLE

推荐答案

您可以通过多种方式进行操作,一种简单的方法是使用带有方括号表示法的对象.

You could just do it in many ways, one simple way would be to use an object with bracket notation.

示例:-

ng-class="{ true: 'vfnz-form--error', false : 'vfnz-form--good'  }[loginForm.username.$invalid]"

或者(因为它不能同时无效和有效):-

Or (since it cannot be both invalid and valid):-

ng-class="{'vfnz-form--error' : loginForm.username.$invalid, 'vfnz-form--good' : loginForm.username.$valid}"

如果只想在表单变脏的情况下执行此操作,则可以添加条件以检查$ pristine/$ dirty,但也可以在输入(以及表单)上使用angular angular类即ng-pristine/ng-dirty,因此您可以使用这些类名定义规则以使其更加具体.

And if you want to do it only if form is dirty you could yes add condition to check for $pristine/$dirty but you could also make use of the class angular adds on the inputs (and on the form as well) i.e ng-pristine/ng-dirty so you could define the rule with these class names to make it more specific.

例如:-

.vfnz-form--error .ng-dirty.something{/*apply bad rules*/} 

这篇关于AngularJS |使用ng-class的条件类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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