title: angularjs: custom directive to check if a username exists
body: <p>I have my registration form with textbox username. I want to do is when the user enter the username, the custom directive will check if the entered username is exists in the database. </p>
  
  <p>directives.js</p>
  
  <pre><code>angular.module('installApp').directive('pwCheck', function ($http) {
    return {
      require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
          elem.on('blur', function (evt) {
            scope.$apply(function () {
            $http({ 
            method: 'GET', 
            url: '../api/v1/users', 
            data: { 
              username:elem.val(), 
              dbField:attrs.ngUnique 
            } 
        }).success(function(data, status, headers, config) {
          ctrl.$setValidity('unique', data.status);
          });
         });
        });
       }
      }
  });
  </code></pre>
  
  <p>If it's exists, my <code>div class = "invalid"</code> will shown in the html form with label "Username already exists."</p>
  
  <p>registration.html</p>
  
  <pre><code>    &lt;form name  = "signupform"&gt;
        &lt;label&gt;{{label.username}}&lt;/label&gt;
          &lt;input type="text" id = "username" name = "username" ng-model="user.username" class="form-control"&gt;&lt;/input&gt;
          &lt;div class="invalid" ng-show="signupform.username.$dirty &amp;&amp; signupform.username.$invalid"&gt;&lt;span ng-show="signupform.username.$error.unique"&gt;Username already exists.&lt;/span&gt;
          &lt;/div&gt;
      &lt;/form&gt;
  </code></pre>
  
  <p>But right now, they are not working :-(,am I doing right? Please advice or suggest me things I should do. Thanks in advance. </p>