Nitesh Rana
Nitesh Rana

Reputation: 512

I want to build a custom angularjs Unique Value Directive

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/

Upvotes: 0

Views: 116

Answers (2)

tanmay
tanmay

Reputation: 7911

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

Upvotes: 1

Mansi Parekh
Mansi Parekh

Reputation: 519

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.

Upvotes: 0

Related Questions