如何显示AngularJs $ asyncValidator返回的数据

时间:2015-02-17 14:35:58

标签: angularjs angular-directive

当表单字段有效时,显示$ asyncValidator返回的数据的最佳方法是什么?

我可以在ngMessage的输入字段旁边显示错误,但是也希望在验证通过时显示Restangular的结果响应。

'use strict';

angular.module('app')
.directive('productionOrder', function(Restangular) {

  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attributes, ngModel) {
      ngModel.$asyncValidators.exists = function(modelValue) {

        return Restangular.one('production_orders', modelValue).get();
      }
    }
  };
});

HTML

<form name="workOrderForm">
<input type="text" name="productionOrderNo" ng-model="work_order.work_order.production_order_no" required production-order ng-model-options="{ debounce: 1000 }">
<div ng-messages="workOrderForm.productionOrderNo.$error">
  <div ng-message="required">Production order no is mandatory</div>
  <div ng-message="exists">Production order not found</div>
</div>
</form>

1 个答案:

答案 0 :(得分:0)

我确信这至少打破了几个最佳做法,但这就是我现在的工作方式。

angular.module('oeeMaster')
  .directive('productionOrder', function($q, Restangular) {

    return {
      restrict: "A",
      require: "ngModel",
      link: function($scope, element, attributes, ngModel) {

        ngModel.$asyncValidators.exists = function(modelValue) {
          var deferred = $q.defer();

          Restangular.one('production_orders', modelValue).get().then(
            function(response) {
              ngModel.part_no = response.part_no;
              deferred.resolve(response);
            }, function() {
              ngModel.part_no = null;
              deferred.reject();
            }
          );

          return deferred.promise;
        }
      }
    };
  });

HTML

<div ng-if="workOrderForm.productionOrderNo.part_no">Part number: {{ workOrderForm.productionOrderNo.part_no }}</div>