0

I want to build a directive that checks for duplicate username. So I have created an index.html file and an uniqueId directive. Now in the directive I am not able to do ngModel.setValidity(). It is getting undefined.

Also I am fetching data from a local json file username.json.

When I console log console.log(ngModel.$setValidity('unique', unique)) I get undefined.

I have created a plunk for the code::

https://embed.plnkr.co/XTPf9PjiMn9if5Y0DaHt/

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

please check plnkr link

If you type [email protected], it will display email already in use. If you type [email protected], it won't show error message. I have changed condition.

3 Comments

No Mansi, It is not showing the message in plunker. What condition have you changed.
Don't know why it is not working for you. I changed this : dataService.checkUniqueValue(keyProperty.key, keyProperty.property, currentValue) .then(function(unique) { if (unique == element.val()) { ngModel.$setValidity('unique', false); } else { ngModel.$setValidity('unique', true); } }, function() { ngModel.$setValidity('unique', true); });
Got it we need to iterate over each value before setting to true or false. Thanks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.