如何将验证错误详细信息传递给查看

时间:2013-11-27 14:23:28

标签: angularjs angularjs-directive angularjs-view

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

将这些细节存储在范围内可能会有效,但根本不适合我。还有更好的方法吗?

指令:

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>

1 个答案:

答案 0 :(得分: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