【问题标题】:angularJS change form input border color on errorangularJS在错误时更改表单输入边框颜色
【发布时间】:2021-04-05 04:35:53
【问题描述】:

这是我第一次使用 bootstrap 和 angularJS,我创建了一个登录表单。如果我的用户名长度不正确,我会在 input 下显示错误。但是,如果显示错误并且我不知道该怎么做,我也想将输入边框颜色更改为红色。如果我可以为单个输入执行此操作,我可以在任何地方使用它

我的用户名输入代码:

      <form name= "logForm">
        <div class="form-group">
          <label for="username">Username:</label>
          <input type="username" class="form-control" id="uname" placeholder="Enter username" name="uname" 
                 ng-minlength= "10" ng-maxlength = "15" ng-model = "uname" required/>

          <span style= "color: #4CAF50" ng-show = "logForm.uname.$valid">Valid</span>
          <span style= "color:red" ng-show= "logForm.uname.$touched && logForm.uname.$error.minlength">
            Min length is 10 
          </span>
          <span style= "color:red" ng-show= "logForm.uname.$touched && logForm.uname.$error.maxlength">
            Max length is 15 
          </span>     

        </div>
     </form>

所以我需要找到一种方法,当错误出现时,我的输入边框为红色,而当我有有效输入时,边框必须为绿色。

【问题讨论】:

    标签: css angularjs forms twitter-bootstrap


    【解决方案1】:

    这可以使用 ng-class 或 ng-style 来完成: 使用 ng-style 的解决方案:

    <input type="username"
        class="form-control"
        ng-style="!(!(uname.length < 10) && !(uname.length > 15)) && {"border" : "1px solid red"} "
        id="uname"
        placeholder="Enter username"
        name="uname"
        ng-minlength="10"
        ng-maxlength="15"
        ng-model="uname"
        required
    />
    

    【讨论】:

      【解决方案2】:

      您可以使用ng-class 向元素添加类。有关此指令的更多信息,请参阅文档:https://docs.angularjs.org/api/ng/directive/ngClass

      在您的情况下,您想在错误可见时添加一些类。您所要做的就是在您的输入中添加类似ng-class="{ 'is-invalid': logForm.uname.$touched &amp;&amp; logForm.uname.$error.minlength }" 的内容。 (请注意,is-invalid 类是官方的引导输入错误类,但不同版本可能会有所不同:https://getbootstrap.com/docs/4.0/components/forms

      <input type="username"
          ng-class="{ 'is-invalid': logForm.uname.$touched && logForm.uname.$error.minlength }"
          class="form-control"
          id="uname"
          placeholder="Enter username"
          name="uname"
          ng-minlength="10"
          ng-maxlength="15"
          ng-model="uname"
          required
      />
      

      如果你只是想添加一些样式而不是类,你可以使用ng-style 指令: https://docs.angularjs.org/api/ng/directive/ngStyle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-20
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        相关资源
        最近更新 更多