Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations:
This is how my code looks like:
<div ng-controller="RootController as root">
<h1>Angular Project</h1>
<div ng-show="{{root.greeting}}">
<p>{{root.greeting}}</p>
</div>
</div>
The Controller part:
(function(){
'use strict';
function RootController(greetingService) {
var vm = this;
vm.greeting = '';
// Initialization 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);
})();
The Service section:
(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 );
})();
My Concerns:
Why isn't my view updating when the timeout completes and the vm.greeting assignment takes place in my controller? I've heard about the concept of "inside Angular vs outside Angular", but I believe I'm still within the Angular environment.
I know about $scope.$apply(), however, I faced the "digest is already in progress" error, which makes me question if there's a better approach.
Should I reconsider how I organize my components? I've tried using broadcasting events over $rootScope and setting up event handlers in the Controller, but it leads to the same issue of the view not reflecting the asynchronous model changes.