1

I'm learning angularjs and trying to append a greeting to h3 tag using Promise. But it doesn't work (no error log).

angular.module('app', []).controller('test', function ($scope) {
  $scope.greeting = 'Hello world!';
  
  let p1 = new Promise(r => r('Hi'));  
  let p2 = new Promise(r => r('Im Gosu'));
  
  Promise.all([p1, p2]).then(p => {
    $scope.greeting = `${p[0]} ${p[1]}`;
    
    console.log(p[0]);
    console.log(p[1]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
  <h3 ng-bind="greeting"></h3>
</div>

What am I missing?

1 Answers1

1

Angular needs to know that your promise has been resolved to trigger a change detection cycle, reevaluate the expression greetingused in the view, detect that it has changed, and update the DOM.

If you use the angular $q service, that's automatic, because every time a $q promise is resolved, the $q angular service triggers the change detection. By using native promises, you're changing the state of your model behind the back of angular.

So, either use $q, or understand what you're doing and add $scope.$apply() at the end of your callback function, to inform angular that you have changed the model.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks! I've read your answer multiple times. That really helps. Before reading your answer I haven't thought it's a feature yet. –  Jun 04 '17 at 16:10