title: How to ensure in AngularJS, that the data is loaded first before it is used?
body: <p>I guess it's a classic JavaScript and asynchronism issue, but I didn't get, how to solve it. I'm building a fronend with AngularJS. Later the date will be retrieved from an API, but now I'm simply read it from a local <code>JSON</code> file. Here is the code:</p>
  
  <p><strong><code>app.js</code></strong></p>
  
  <pre><code>(function() {
      var app = angular.module('portfolio', []);
  
      app.controller('ProjectItemController', function() {
          this.projectItemData = dataProjectItem;
          console.log(dataProjectItem);
      });
  
      var dataProjectItem;
      var xhr = new XMLHttpRequest();
      xhr.open('GET', config['base_url'] + '/dummy-data/project-item.json');
      xhr.onload = function() {
          dataProjectItem = JSON.parse(xhr.responseText);
      };
      xhr.send();
  
  })();
  </code></pre>
  
  <p><strong><code>list.phtml</code></strong></p>
  
  <pre><code>&lt;div id="projects" ng-app="portfolio"&gt;
      &lt;div class="projectItem" ng-controller="ProjectItemController as projectItem"&gt;
          &lt;div class="project-image"&gt;&lt;img ng-src="{{projectItem.projectItemData._embedded.images[0].src}}" /&gt;&lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>The problem is, that on the server (and sometimes locally as well), the data has not yet been loaded and script is already trying to use <code>projectItemData</code>.</p>
  
  <p>I've tried to solve it with a anonymous function, but it hasn't worked:</p>
  
  <pre><code>app.controller('ProjectItemController', function() {
      this.projectItemData = (function () {
          var dataProjectItem;
          var xhr = new XMLHttpRequest();
          xhr.open('GET', config['base_url'] + '/dummy-data/project-item.json');
          xhr.onload = function() {
              dataProjectItem = JSON.parse(xhr.responseText);
          };
          xhr.send();
          return this.dataProjectItem;
      })();
  });
  </code></pre>
  
  <p><s>(1) How to make the script always load the data first and only then use it? And since it's currently taking place in the AngularJS context: (2) Is there a specific Angular solution for this problem?</s></p>
  
  <p><strong>EDIT</strong></p>
  
  <p><strong>How to solve this problem in AngularJS?</strong></p>