I'm new to AngularJs and also fairly new to promises. From the start, my
async validator seemed coded correctly. It still seems that way. And yet
it wasn't working. After six hours of trying variations, I finally found
one that works (I made a slight change to the promise-logic) but I don't
see any relevant differences from my original code. I guess I don't
understand promises.
This (silly) validator has the server confirm that the user typed in at
least two words in the Product Description field.
Here's the code that doesn't work correctly, in the sense that form.$valid
always returns false, even with correct data, and when I put in bad data,
the error message doesn't even show.
mod.directive('atLeastTwoWords', ['$http', '$q', function ($http, $q) {
return { //async validator
require: 'ngModel',
link: function ($scope, element, attrs, ngModel) {
ngModel.$asyncValidators.atLeastTwoWords = function
(modelValue, viewValue) {
var description = modelValue || viewValue;
var data = { description: description };
var promise = $http.post("/Home/AtLeastTwoWords", data);
promise.then(function (response) {
if (response.data == true) return true;
else return $q.reject("At least two words needed");
});
return promise;
}//ends ngModel function block
}//ends link funcion
}//ends return json
}]);
Notice the promise is split across two lines of code. If I merge those two
lines into one line, by simply removing the semicolon and the word 'promise'
var promise = $http.post("/Home/AtLeastTwoWords", data)
.then(function (response) {
then the code works fine! I must be losing my mind. I see no relevant
differences. I've been beating my head against the wall for about six hours
on this issue. I'm using AngularJS v1.6.4.
In both cases the seq of code is the same - the breakpoints fire in all the
same order, as far as I can tell, and all logic branching is the same.
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.