【问题标题】:Adding class dynamically based on condition in angular js app根据角度js应用程序中的条件动态添加类
【发布时间】:2015-05-11 20:02:10
【问题描述】:

在我的一个应用程序中,我需要在具有任何数据时添加一个特定的类,而不管它使用 AngularJS 的输入类型(电子邮件、文本)如何:

this plunk 中,只需在文本框中输入任何内容即可更改边框颜色。

参考代码

<body ng-app="">
    <input type='text' ng-model='Custom' ng-class="{red : Custom.length}">
    <label ng-bind='Custom'></label>
</body>

以类似的方式,我希望它适用于所有输入类型。

如果是电子邮件字段。当用户输入错误的电子邮件时,它不起作用,因为模型在无效时不会获得价值。

【问题讨论】:

标签: javascript angularjs validation


【解决方案1】:

这是因为在输入包含有效电子邮件地址之前,ng-model 为空。

克服它的一种方法是检查 $viewValue 变量,如下所示:

<form name="myForm" novalidate>
    <input name="email" type='email' ng-model='email' 
           ng-class="{red : myForm.email.$viewValue.length}">
</form>

【讨论】:

    【解决方案2】:

    在模型有效之前,Angular 不会将值绑定到模型,因此在输入类型的情况下,字段长度将为 0,直到您输入正确的电子邮件。但是你可以使用 $viewValue 值来做到这一点,请看下面的演示

    .red {
      border-color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <body ng-app="">
      <form name="myform">
        <input type='text' ng-model='Custom' ng-class="{red : Custom.length}">
        <input type='email' ng-model='email' ng-class="{red : myform.email.$viewValue}" name="email">
    
        <label ng-bind='Custom'></label>
      </form>
    </body>

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2014-11-27
      • 1970-01-01
      • 2018-06-22
      相关资源
      最近更新 更多