добавление ng-недопустимого класса при несоответствии входных данных


Angular автоматически добавляет класс ng-invalid в поле ввода электронной почты, если он недействителен, как можно добавить класс ng-invalid в input#confirmEmail, если он не соответствует input#email, и удалить, если они совпадают.

В принципе, я не обязан показывать какие-либо сообщения в случае несоответствия, просто хочу выделить поле ввода через класс ng-invalid и проверить форму на основе этого.

<li>
    <label for="email">Email</label>
    <input type="email" id="email" name="email" ng-model="data.account.email" ng-required="">
</li>
<li>
    <label for="confirmEmail">Confirm Email</label>
    <input type="email" id="confirmEmail" name="confirmEmail" ng-model="data.account.confirmEmail">
</li>
3 2

3 ответа:

Расширяю свой комментарий, чтобы ответить. Вот простая проверка директивы compare, которая может быть использована для проверки формы и входных данных, если она не соответствует введенному значению. Использование ngModelController по (>= В1.3.x) $validators это становится легко обрабатывать.

Директива будет выглядеть так:

.directive('comparewith', ['$parse', function($parse){
  return {
     require:'ngModel',
      link:function(scope, elm, attr, ngModel){
        //Can use $parse or also directly comparing with scope.$eval(attr.comparewith) will work as well
        var getter = $parse(attr.comparewith);

        ngModel.$validators.comparewith = function(val){
          return val === getter(scope);
        }
        scope.$watch(attr.comparewith, function(v, ov){
          if(v !== ov){
             ngModel.$validate();
          }
        });
      }
  }
}]);

И использовать его как:

<li>
    <label for="email">Email</label>
    <input type="email" id="email" name="email" 
          ng-model="data.account.email" required>
</li>
<li>
    <label for="confirmEmail">Confirm Email</label>
    <input type="text" id="confirmEmail" name="confirmEmail"
           comparewith="data.account.email" required 
           ng-model="data.account.confirmEmail">
</li>

Демо

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.submit = function(form) {
    if (form.$invalid) {
      alert("oops password and confirm must match and must be valid");
    } else {
      alert("Äll good!!");
    }
  };
}).directive('comparewith', ['$parse', function($parse) {
  return {
    require: 'ngModel',
    link: function(scope, elm, attr, ngModel) {
      var getter = $parse(attr.comparewith);

      ngModel.$validators.comparewith = function(val) {
        return val === getter(scope);
      }
      
      scope.$watch(attr.comparewith, function(v, ov){
         if(v !== ov){
            ngModel.$validate();
         }
      });
    }
  }
}]);
/* Put your css in here */

form.ng-invalid {
  border: 1px solid red;
  box-sizing: border-box;
}
input.ng-invalid {
  border: 2px solid red;
  box-sizing: border-box;
}
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <form name="form" ng-submit="submit(form)" novalidate>
    <ul>
      <li>
        <label for="email">Email</label>
        <input type="email" id="email" name="email" ng-model="data.account.email" required>
      </li>
      <li>
        <label for="confirmEmail">Confirm Email</label>
        <input type="text" id="confirmEmail" name="confirmEmail" comparewith="data.account.email" required ng-model="data.account.confirmEmail">
      </li>
    </ul>
    <button>Submit</button>
  </form>
</body>

</html>

Вы можете использовать ng-class и просто проверить, равны ли модели:

ng-class="{'ng-invalid' : data.account.confirmEmail != data.account.email}"

Вы можете добавить все это в html

<li>
   <label for="email">Email</label>
   <input type="email" id="email" name="email" ng-model="data.account.email" 
          ng-required="">
</li>
<li>
   <label for="confirmEmail">Confirm Email</label>
   <input type="email" id="confirmEmail" name="confirmEmail" 
          ng-model="data.account.confirmEmail" ng-pattern="{{data.account.email}}">

   <div ng-messages="data.account.confirmEmail.$error">
        <div ng-message="pattern">Confirm email must match email.</div>
   </div>
</li>

Нужно ngMessages для