You need to iterate through the users present in JSON. And, if your currentValue matches any of those, you need to set it as invalid using $setValidity. Like this:
dataService.getUsers().then(function(currentusers) {
console.log(currentusers)
//Ensure value that being checked hasn't changed
//since the Ajax call was made
if (currentValue == element.val()) {
currentusers.forEach(function(user) {
if (currentValue === user.property) {
ngModel.$setValidity('unique', false)
}
});
}
}, function() {
//Probably want a more robust way to handle an error
//For this demo we'll set unique to true though
ngModel.$setValidity('unique', true);
});
});
Also, your service was getting the JSON every time. Alternatively, you can store your JSON response in a variable inside your angular service (which is a singleton) so it's faster than before. Like this,
dataFactory.getUsers = function() {
var deferred = $q.defer()
if (angular.isDefined(savedResults)) {
deferred.resolve(savedResults.data);
return deferred.promise;
} else {
return $http.get(serviceBase).then(
function(results) {
savedResults = results
return results.data;
});
}
};
Here, we return a resolved promise if data is already available. It will get the JSON for the first time and will use from within.
working plunker