title: how to do live responsive custom validation of form fields in angular
body: <p>I have a form field that I want validated against a rest api as the user types in the form field.  Sort of like an auto-complete but an auto-verify instead.  I've started to lay some of the code down in angular but not sure how to observe the input onchange in angular or how to set the inavlid property of things.</p>
  
  <p>Here's what I have so far</p>
  
  <pre><code>app.directive('purchaseCode', function() {
      return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
  
              ctrl.$parsers.unshift(function(viewValue) {
                  if (CODE_REGEXP.test(viewValue)) {
  
                      //how do I get the $http context/scope to to an ajax request here?
                      $http.get('check/user.code').success(function(data) {
                         ctrl.$setValidity('purchase_code', data.is_valid);
  
                      });
                      return viewValue;
                  } else {
                      ctrl.$setValidity('purchase_code', false);
                      return undefined;
                  }
              });
          }
      };
  });
  function Controller($scope, $routeParams, $http) {
      $scope.master = {};
  
  
      $scope.update = function(user) {
          $scope.master = angular.copy(user);
      };
  
      $scope.reset = function() {
          $scope.user = angular.copy($scope.master);
      };
  
      $scope.isUnchanged = function(user) {
          return angular.equals(user, $scope.master);
      };
  
      $scope.reset();
  }
  </code></pre>
  
  <p>and the HTML</p>
  
  <pre><code>&lt;div class="container" ng-app&gt;
  
      &lt;form no-validate id="myform" name='form' action="/upload"  method="POST" role="form" ng-controller="Controller"&gt;
  
  
          &lt;div class="form-group has-error"&gt;
              &lt;label class="control-label" for="purchase_code"&gt;Purchase code&lt;/label&gt;
              &lt;input type="text" class="form-control" id="purchase_code" placeholder="purchase code"
                     ng-model="user.code"
                     purchase-code
                     name="code"&gt;
          &lt;/div&gt;
  
          &lt;button type="submit" class="btn btn-block btn-primary" ng-click="update(user)"
                  ng-disabled="form.$invalid || isUnchanged(user)"&gt;Submit&lt;/button&gt;
      &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>What do I do to have it watch the event of the form field being changes.  Also a bonus question: how do I keep it from showing the invalid/dirty state until it gets to be more than 3 characters in length?</p>
  
  <p>I tried looking at the custom validator sample on <a href="http://docs.angularjs.org/guide/forms" rel="nofollow">http://docs.angularjs.org/guide/forms</a> but it doesn't seem to work if you copy and paste their code in verbatim.</p>