How to set Twitter Bootstrap class=error based on AngularJS input class=ng-invalid?

后端 未结 2 2140
孤街浪徒
孤街浪徒 2021-02-18 21:32

I have a problem where my CSS is not taking effect (in Chrome), and I think there is some conflict with Twitter Bootstrap.

input.ng-invalid {
    border-color: r         


        
相关标签:
2条回答
  • 2021-02-18 22:24

    You can easily do it with ng-class directive:

    <form name="myForm">
      <div class="control-group" ng-class="{ error: myForm.salt.$invalid }">
        <label class="control-label" for="salt">Salt: </label>
        <div class="controls">
          <input type="text" name="salt" ng-model="salt" ng-pattern="hexPattern">
        </div>
      </div>
    </form>
    

    http://plnkr.co/edit/RihsxA?p=preview

    EDIT

    Example with bootstrap 3.3.5 and angular 1.4.2:

    <form name="myForm">
      <div class="form-group" ng-class="{ 'has-error': myForm.salt.$invalid }">
        <label class="control-label" for="salt">Salt: </label>
        <input class="form-control" type="text" name="salt" ng-model="salt" ng-pattern="hexPattern">
      </div>
    </form>
    

    http://plnkr.co/edit/5JNCrY8yQmcnA9ysC7Vc?p=preview

    0 讨论(0)
  • 2021-02-18 22:24

    I think a better solution is to just add your own CSS rules. It makes the code much simpler and, as a bonus, you can set the rule to only apply to "dirty" elements. That way fields will only be highlighted after the user has tried to enter something.

    In my application I've just added this css, based on an example in the AngularJS forms documentation.

    /* Forms */
    .ng-invalid.ng-dirty {
      border-color: red;
      outline-color: red;
    }
    .ng-valid.ng-dirty {
      border-color: green;
      outline-color: green;
    }
    
    0 讨论(0)
提交回复
热议问题