我如何能类添加到输入如果输入与AngularJS改变? [英] How can I add a class to an input if the input is changed with AngularJS?
问题描述
I codeD在我的表格如下:
I coded the following in my form:
<td><input type="text" ng-model="row.title" /></td>
当我看着自己的DOM与Chrome开发者工具,我看到以下内容:
When I look at my DOM with Chrome developer tools I see the following:
<input type="text" ng-model="row.title" class="ng-pristine ng-valid">
我怎样才能让这个时,有一个变化的输入中添加了一个类的输入制作的?
How can I make it so that when there is a change made to the input that the input has a class added to it?
推荐答案
有两个好方法来解决这个问题:
There are two good ways to approach this problem:
1。使用内置的 NG-脏
类元素的角看跌期权。
1. Use the built-in ng-dirty
class that Angular puts on the element.
当你通过改变角度管理的输入,它增加了一些CSS类的输入各种状态。这些措施包括:
When you change an input managed by Angular, it adds some CSS classes to the input for various states. These include:
-
NG-质朴
- 输入没有被修改 -
NG-脏
- 输入已被修改
ng-pristine
- the input has not been modifiedng-dirty
- the input has been modified
所以,如果你可以修改你的CSS将基于该 .ng脏
类,你是好去。
So, if you can modify your CSS to be based off the .ng-dirty
class, you're good to go.
2。使用格式
指令与 $脏
标记。
2. Use a form
directive with the $dirty
flag.
当您使用格式
元素,角分配的 的FormController
实例与相同的名称,窗体上的名称
属性的范围的;在表单中的每个输入获取具有相同的名称名称输入
属性附加到的FormController实例作为属性,一次。例如,
When you use a form
element, Angular assigns a FormController
instance on the scope with the same name as the name
attribute on the form; each input inside the form gets attached to that FormController instance as a property, again with the same name as the name
attribute on the input. For example,
<form name="myForm">
<input type="text" name="myInput">
</form>
为您提供
$scope.myForm.myInput
每个输入酒店有一些它的的的它的属性,包括 $质朴
和 $脏$的C $ C>;这些工作就像上面列出的CSS类。因此,您可以检查
$脏
标志上的输入,并使用纳克级
一类有条件地适用于的元素。举个例子:
Each input property has some of its own properties on it, including $pristine
and $dirty
; these work just like the CSS classes listed above. Thus, you can check for the $dirty
flag on the input and use ng-class
to conditionally apply a class to the element. An example:
<div ng-controller="MainController">
<form name="myForm">
<input name="myInput" ng-model="model" ng-maxlength="3"
ng-class="{changed: myForm.myInput.$dirty}">
</form>
</div>
您可以在这里找到工作的例子: http://jsfiddle.net/BinaryMuse/BDB5b/
You can find a working example here: http://jsfiddle.net/BinaryMuse/BDB5b/
这篇关于我如何能类添加到输入如果输入与AngularJS改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!