Inside an Angular 1.3 sample, I noticed the usage of ‘$pending’. Strange, never seen that object before. Let’s find out where it’s useful!
‘$pending’ finds it use together with the new $asyncValidator pipeline. The $asyncValidator pipeline contains validation rules that will typically be rules that needs server-side logic to make a decision. As long as the async validation rule promise isn’t resolved $pending will return true. This can be useful to give the users a visual indication while the validation rule is executing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="text" name="userName" | |
ng-model="registration.userName" | |
required is-unique /> | |
<div ng-if="registrationForm.userName.$pending"> | |
Checking.... | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.directive("isUnique", function($q, $http) { | |
return { | |
restrict: "A", | |
require: "ngModel", | |
link: function(scope, element, attributes, ngModel) { | |
ngModel.$asyncValidators.isUnique = function(modelValue, viewValue) { | |
return $http.post('/username-check', {username: viewValue}).then( | |
function(response) { | |
if (!response.data.validUsername) { | |
return $q.reject(response.data.errorMessage); | |
} | |
return true; | |
} | |
); | |
}; | |
}); |