0

在自定义验证指令中,我确保输入的值不会与数据库中的其他值冲突。如果是这样,我想告诉用户不仅有冲突,而且还有与之冲突的项目的名称。

将这些细节存储在范围中可能会起作用,但对我来说似乎根本不对。有没有更好的办法?

指示:

angular.module('myApp')
  .directive('conflictcheck', function (myServer) {
    return {
      require: 'ngModel',
      link: function (scope, elm, attrs, ctrl) {
        ctrl.$parsers.unshift(function (viewValue) {
          var conflict = myServer.getConflict(viewValue);
          if (!conflict) {
            ctrl.$setValidity('conflictcheck', true);
            return viewValue;
          } else {
            ctrl.$setValidity('conflictcheck', false);

            // pass additional info regarding the conflict here

            return undefined;
          }
        });
      }
    };
  });

看法:

<form name="myform" action="#">
  <input ng-model="foo" conflictcheck />
  <div ng-if="myform.foo.$error.conflictcheck">
     Error: Foo conflicts with XXXXXXXX!
  </div>
</form>
4

1 回答 1

1

验证错误由FormController处理,因此将所有与验证相关的数据保留在表单对象本身内是合理的。这可以通过将任意数据附加到myform实例来实现:

app.factory('myServer', function(){
  return {
    getConflict: function(viewValue){
      var comparedAgainst = 'existing@email.com';
      if(viewValue === comparedAgainst){
        return comparedAgainst;
      }
    }
  }
});

app
  .directive('conflictcheck', function (myServer) {
    return {
      require: ['ngModel', '^form'],
      link: function (scope, elm, attrs, ctrls) {
        var ngModelCtrl = ctrls[0];
        var ngFormCtrl = ctrls[1];

        ngModelCtrl.$parsers.unshift(function (viewValue) {
          // getConflict returns conflicting value
          var conflict = myServer.getConflict(viewValue);

          if (!conflict) {
            ngModelCtrl.$setValidity('conflictcheck', true);
            return viewValue;
          } else {
            ngModelCtrl.$setValidity('conflictcheck', false);
            // We attach validation-specific data to arbitrary data property
            ngFormCtrl.foo.data = {
              conflictcheck: conflict
            };

            return undefined;
          }
        });
      }
    };
  });
<form name="myform" novalidate>
  Email: 
  <input ng-model="foo" name="foo" conflictcheck />
  <div ng-show="myform.foo.$error.conflictcheck">
   Error: Foo conflicts with {{myform.foo.data.conflictcheck}}!
  </div>
</form>

Plunker

于 2013-11-27T15:27:56.747 回答