1
1
angular . module ( 'angular-async-validation' )
2
2
3
- . directive ( 'asyncValidation' , [ '$log' , '$http' , function ( $log , $http ) {
3
+ . directive ( 'asyncValidation' , [ '$log' , '$q' , '$ http', function ( $log , $q , $http ) {
4
4
5
5
var directive = {
6
6
restrict : 'A' ,
7
7
require : 'ngModel' ,
8
+ scope : { asyncValidation : '=' } ,
8
9
link : _link
9
10
} ;
10
11
@@ -15,16 +16,13 @@ angular.module('angular-async-validation')
15
16
// The async validation function
16
17
var validationFunction ;
17
18
18
- // The attribute value
19
- var asyncValidation = scope . $eval ( attrs . asyncValidation ) ;
20
-
21
- if ( ! asyncValidation || ! asyncValidation . length || typeof asyncValidation === 'undefined' ) {
19
+ // Check if the argument passed satisfy the requirements
20
+ if ( ! scope . asyncValidation && ! angular . isString ( scope . asyncValidation ) && ! angular . isFunction ( scope . asyncValidation ) ) {
22
21
$log . warn ( 'angular-async-validation: missing or empty argument in async-validation attribute on:' , elem ) ;
23
22
return ;
24
23
}
25
24
26
- // If no options are specified
27
- // set to the defaults
25
+ // If no options are specified set to the defaults
28
26
if ( ! ngModel . $options || ! ngModel . $options . getOption ( 'debounce' ) ) {
29
27
30
28
ngModel . $options = ngModel . $options . createChild ( {
@@ -35,17 +33,25 @@ angular.module('angular-async-validation')
35
33
36
34
}
37
35
38
- // If is a string use it as
39
- // path for ajax request
40
- if ( angular . isString ( asyncValidation ) ) {
36
+ // If is a string use it as path for http request
37
+ if ( angular . isString ( scope . asyncValidation ) ) {
41
38
42
39
validationFunction = function ( modelValue , viewValue ) {
43
40
44
41
// get the value
45
42
var value = modelValue || viewValue ;
46
43
44
+ // Consider empty models to be valid
45
+ // for this type of validation
46
+ if ( ngModel . $isEmpty ( value ) ) {
47
+ return $q . resolve ( ) ; ;
48
+ }
49
+
50
+ // Init the deferred object
51
+ var deferred = $q . defer ( ) ;
52
+
47
53
// build the url
48
- var url = asyncValidation . replace ( ':value' , value ) ;
54
+ var url = scope . asyncValidation . replace ( ':value' , value ) ;
49
55
50
56
// run the request
51
57
return $http . get ( url , {
@@ -62,8 +68,8 @@ angular.module('angular-async-validation')
62
68
63
69
// If is a function defined by users
64
70
// assign it to asyncValidators
65
- if ( angular . isFunction ( asyncValidation ) ) {
66
- validationFunction = asyncValidation ;
71
+ if ( angular . isFunction ( scope . asyncValidation ) ) {
72
+ validationFunction = scope . asyncValidation ;
67
73
}
68
74
69
75
// Add the async validator
0 commit comments