title: Angular JS: Chaining promises and the digest cycle
body: <h2><strong>NOTE:</strong> the fiddle uses an old version of Angular, and that it's not working any more because as of 1.2 the Angular template engine does not handle promises transparently.</h2>
  
  <p>I'm looking into chaining promises to populate my scope, and then having the scope automatically update the dom.  </p>
  
  <p>I'm running into problems with this though.. If I call "then" on an already resolved promise, it creates a new promise (that will call the success function asynchronously but almost immediately).  I think the problem is that we've already left the digest cycle by the time the success function is called, so the dom never updates.  </p>
  
  <p>Here is the code:</p>
  
  <pre><code>&lt;div ng-controller="MyCtrl"&gt;
      Hello, {{name}}! &lt;br/&gt;
      {{name2}}&lt;br/&gt;
      &lt;button ng-click="go()"&gt;Clickme&lt;/button&gt;&lt;br/&gt;
      {{name3}}
  &lt;/div&gt;
  
  var myApp = angular.module('myApp',[]);
  
  function MyCtrl($scope, $q) {
      var data = $q.defer();    
      setTimeout(function() {$scope.$apply(data.resolve("Some Data"))}, 2000);
      var p = data.promise;
  
      $scope.name = p.then(angular.uppercase);
      $scope.name2 = p.then(function(x) { return "Hi "+x;});
      $scope.go = function() {
              $scope.name3 = p.then(function(x) { 
                  // uncomment this to make it work:
                  //$scope.$apply();
                  return "Finally: "+x;
              });
      };
   }
  </code></pre>
  
  <p><a href="http://jsfiddle.net/QZM4d/" rel="nofollow noreferrer">http://jsfiddle.net/QZM4d/</a></p>
  
  <p>Is there some way to make this work without calling $apply every time I chain promises?</p>