title: writing a directive for validating image url
body: <p>this is the first directive I'm writing for AngularJS.
  I want to check if an image url inserted into a text input is valid.</p>
  
  <p>this is what I have so far:</p>
  
  <pre><code>angular.module('directives', [])
  .directive('imageUrlVerify', function() {
      return {
          restrict: 'A',
          require: 'ngModel',
          link: function(scope, element, attrs, ctrl) {
              var image = new Image();
  
              scope.$watch(function() {
                  if (ctrl.$viewValue) {
                      image.src = ctrl.$viewValue;
  
                      if (image.complete) {
                          scope[attrs.imageValid] = true;
                      } else {
                          scope[attrs.imageValid] = false;
                      }
                  } else {
                      scope[attrs.imageValid] = false;
                  }
              });
          }
      }
  })
  </code></pre>
  
  <p>and I use it:</p>
  
  <pre><code>&lt;input type="text" ng-model="imageUrl" placeholder="Image URL..." data-image-valid="imageOk" image-url-verify&gt;
  </code></pre>
  
  <p>This is actually working, but as my first directive I want to make sure that I'm doing things the right way...</p>
  
  <p>am I missing something ?</p>
  
  <p>EDIT: following @Josh-David-Miller 's answer I came up with this:</p>
  
  <pre><code>angular.module('directives', [])
  .directive('imageUrlVerify', function() {
      return {
          restrict: 'A',
          replace: true,
          scope: { url: '=', imageValid: '=' },
          template: '&lt;input ng-model="url" placeholder="Image URL..."/&gt;',
          link: function(scope, element, attrs) {
              var image = new Image();
  
              scope.$watch('url', function() {
                  scope.imageValid = false;
              });
  
              element.on( 'blur', function() {
                  image.src = scope.url;
              });
  
              image.onload = function() {
                  scope.$apply(function() {
                      scope.imageValid = true;
                  });
              };
  
              image.onerror = function() {
                  scope.$apply(function() {
                      scope.imageValid = false;
                  });
              };
          }
      }
  })
  </code></pre>
  
  <p>and use it like:</p>
  
  <pre><code>&lt;input image-url-verify url="imageUrl" image-valid="imageOk" /&gt;
  </code></pre>
  
  <p>does it look better? anywhere else to improve?</p>