title: How do you handle asynchronous data in directives for AngularJS
body: <p>This is a similar question to <a href="https://stackoverflow.com/questions/12220521/angularjs-how-to-handle-long-running-requests-for-data-needed-in-controller-se">this one</a>. I'm still seeing some issues with asynchronous data in my directives. Basically I have directives that I want to pass data into, and this data is fetched asynchronously. I started doing this with the scope property on the directive like this:</p>
  
  <pre><code>scope: {
      myAsyncData: '='
  }
  </code></pre>
  
  <p>In the link function I added a <code>$watch</code> so I could update my model based on a value is in the scope. Something like this:</p>
  
  <pre><code>scope.$watch(scope.foo, function() {
      //logic based on myAsyncData
  }
  </code></pre>
  
  <p>When I did this, I started getting javascript errors because the asynchronous data hadn't returned yet. This is what prompted me to post the question linked above. So, I then changed my <code>$watch</code> to something like this:</p>
  
  <pre><code>scope.$watch(scope.foo, function() {
      if (angular.isDefined(scope.myAsyncData))
      {
          //logic based on myAsyncData
      }
  }
  </code></pre>
  
  <p>When I do this, I don't get the javascript errors. However, the <code>$watch</code> doesn't get run again when the data is returned, and so my view doesn't reflect the model correctly. I tried assigning<code>$scope.foo</code> in a <code>$timeout</code> to trigger the watch after the data is returned, but that seems too dependent on timing and is not very robust.</p>
  
  <p>My question is just what is the correct way of interacting with asynchronous data in the directive? I've seen some examples that get the data in the directive like this:</p>
  
  <pre><code>scope.$eval(attrs.myAsyncData);
  </code></pre>
  
  <p>This doesn't seem to change anything. Is there anything fundamentally different with this than the <code>myAsyncData: '='</code> above?</p>
  
  <p>I've started to wonder if I should just get the data through services, but it seems like there would be the exact same issues. I've also had the thought of getting the data directly in the directive, but I don't want to directive to be responsible for getting the data. I only want the directive to be responsible for displaying the data and updating the view as the user interacts with it.</p>
  
  <p>I may be missing something obvious on how this should be done, so any input would me much appreciated.</p>