Controllers are created synchronously (I assume), so there should be no difficulty in executing some code after that.
This is an erroneous assumption. The AngularJS framework regularly creates and destroys directives and their controllers throughout the life of the application. ng-repeat , ng-if , ng-include , etc. all create and destroy directives containing the DOM. If your widget is part of ng-repeat , its controller receives several instances, once for each element in the list that ng-repeat looking at.
To save data that is stored throughout the life of the application, store it in the service. (Or on $rootScope ; not recommended, but an option.) Controllers cannot assume that they were running at boot time. They need to “catch up” and subscribe to the changes.
Keep persistent data in the factory service and provide setter and getter functions.
angular.module("app").factory("padService", function () { //Store service status here var status = "none-yet"; function setStatus(s) { status = s; return status; }; function getStatus() { return status; }; return { setStatus: setStatus, getStatus: getStatus }; });
In your "widget", enter the service, subscribe to the changes and "catch up."
angular.module("app").directive("widget", function() { function widgetController($scope, padService) { //subscribe with $watch $scope.$watch(padService.getStatus, function(newStatus) { //catch-up and react to changes case (newStatus) { "authenticated": // Do stuff related to authenticated state break; "ready": // Do stuff related to pad ready state break; "error": // Do stuff related to error state break; default: // Do something else } $scope.message = newStatus; }; }; return { templateUrl: 'app/widget.html', restrict: 'E', controller: widgetController } });
When the directive first registers a listener using $watch , the AngularJS framework executes the watch function (in this case padService.getStatus ) and performs the function of a listener. This allows the directive to catch up with the current status of the service.
In each cycle, the AngularJS framework digest executes padService.getStatus . If the status has changed, the environment acts as a listener with the new status as the first parameter. This allows the directive to respond to changes.
You cannot assume that a directive and its controller are created synchronously. But you know that this service is created, and its constructor function is executed before it is introduced into the controller.