title: Angular promises - cannot read property then of undefined
body: <p>I'm trying to display the result of a promise in the view, but I get this exception. Other cases of this exception I've found on Google / SO are caused by mistakes I don't see in my code.</p>
  
  <p>I've verified I am using promises, I am resolving the promise inside of the function passed to $timeout, I am returning the promise from the function getData() and not the function that resolves the promise.</p>
  
  <p>Thanks in advance. </p>
  
  <p><strong>Viewer</strong></p>
  
  <pre><code>&lt;html ng-app="controller" ng-controller="MyController as controller"&gt;
  &lt;head&gt;
    &lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="controller.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="services.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    {{data}}
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>Controller (controller.js)</strong></p>
  
  <pre><code>   angular.module('controller', ['services'])
      .controller('MyController', ['MyService', function(MyService) {
  
        MyService.getData().then(function(data) {
          $scope.data = data;
        });
      }]);
  </code></pre>
  
  <p><strong>Service (services.js)</strong></p>
  
  <pre><code>angular.module('services', [])
  .factory('MyService', function($q, $timeout){
    var getData = function getData() {
  
      var deferred = $q.defer;
  
      $timeout(function () {
        deferred.resolve('Foo');
      }, 5000);
  
      return deferred.promise;
    };
  
    return {
      getData: getData
    };
  });
  </code></pre>
  
  <p><strong>Exception stack trace</strong></p>
  
  <pre><code>TypeError: Cannot read property 'then' of undefined
      at new &lt;anonymous&gt; (controller.js:5)
      at Object.e [as invoke] (angular.js:4219)
      at $get.x.instance (angular.js:8525)
      at angular.js:7771
      at q (angular.js:334)
      at M (angular.js:7770)
      at g (angular.js:7149)
      at angular.js:7028
      at angular.js:1460
  </code></pre>