2014-09-25 59 views
2

想知道如何處理$parsers中的異步函數。 以下代碼不會更新範圍。

我正在使用AngularJS 1.2,因此無法使用新的和花哨的1.3功能。

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

標記:

<input type="text" name="test" ng-model="test" parse> 

指令:

app.directive('parse', function($timeout) { 
    return { 
    require: 'ngModel', 
    link: function(scope, element, attrs, ctrl) { 
     ctrl.$parsers.unshift(function(viewValue) { 
     $timeout(function() { 
      return viewValue; 
     }); 
     }); 
    } 
    }; 
}); 
+0

你能詳細介紹一下你的場景嗎?你可以調用$ setViewValue(value);模型控制器更新模型數據,但輸入內容不變。 – Chandermani 2014-09-25 12:58:09

+0

你不能那樣做。你能否擺脫更多的背景? – PSL 2014-09-25 13:01:01

+0

這是一個指令,用於對輸入值的可用性進行異步查找。我基本上想從角度v1.3 $ asyncValidators,但我堅持與v1.2 :( 我有一個「解決方法」,但想知道如何正確處理這個問題:) 解決方法是剛剛返回viewValue無論如何。所以'function(viewValue){validatorAsync(viewValue);返回viewValue; }' – 2014-09-25 13:21:31

回答

0

如果您正在尋找異步驗證功能,我不喜歡的東西,前一段時間和釋放它作爲一個圖書館。檢查自定義遠程驗證器directive here

基本思想是從服務器收到驗證結果後使用ngModelController $ setValidity。這是指令源代碼

.directive('customRemoteValidator', [function() { 
    return { 
     restrict: 'A', 
     require: 'ngModel', 
     link: function (scope, elm, attr, ngModelCtrl) { 
      var validateFunctionNames = attr["remoteValidateFunctions"].split(","); 
      var validatorNames = attr["customRemoteValidator"].split(","); 
      ngModelCtrl.$parsers.push(function (value) { 
       angular.forEach(validateFunctionNames, function (functionName, index) { 
        if (!scope[functionName]) { 
         console.log('There is no function with ' + functionName + ' available on the scope. Please make sure the function exists on current scope or its parent.'); 
        } else { 
         var result = scope[functionName](value); 
         if (result.then) { 
          result.then(function (data) { //For promise type result object 
           ngModelCtrl.$setValidity(validatorNames[index], data); 
          }, function (error) { 
           ngModelCtrl.$setValidity(validatorNames[index], false); 
          }); 
         } 
        } 
       }); 
       return value; 
      }); 
     } 
    }; 
}])