Here's my setup -- I have a controller that is using a service that does some work and then returns data asynchronously. In this case, the data is returned by a timeout, but in real life this would do something more interesting:
View:
<div ng-controller="RootController as root">
<h1>Angular Project</h1>
<div ng-show="{{root.greeting}}">
<p>{{root.greeting}}</p>
</div>
</div>
Controller:
(function(){
'use strict';
function RootController(greetingService) {
var vm = this;
vm.greeting = '';
// startup logic
activate();
function activate() {
greetingService.greeting().then(
function( response ) {
vm.greeting = response;
},
function( error ) {
vm.greeting = error;
}
);
}
}
RootController.$inject = ['greeting'];
angular.module('app.core').controller('RootController', RootController);
})();
Service:
(function() {
'use strict';
// Greeting Service
function greeting( $timeout ) {
// public API
var service = {
greeting: greeting
};
return service;
// internal functions
function greeting() {
return $timeout( function() {
return 'Hello world!';
}, 1000 );
}
}
temp.$inject = ['$timeout'];
angular.module('app.core').factory( 'greeting', greeting );
})();
Questions:
Why is it that my view is not updating when the timeout resolves and the vm.greeting assignment occurs in my controller? I've seen people describe "inside Angular vs outside Angular", but it would seem to me that I haven't gone "outside Angular" here.
I'm aware that I can call $scope.$apply(), but I've encountered the "digest is already in progress" error, and again it doesn't seem like I should have to do this.
Is there a better way I should be organizing my components? I have also experimented with broadcasting an event over $rootScope and writing an event handler in the Controller, but this arrangement exhibits the same outcome (namely the view is not updated when the asynchronous model change occurs).