简体   繁体   中英

Angularjs adding callback after controller has been loaded from outside controller

Is it possible to add a callback to be called after a controller has been loaded in angular? I want to listen such an event from outside that controller however!

I'm integrating our application with an existing angular application and I don't want to modify its source files. To that end I need to be able to take loaded controllers and enhance their scopes with custom functionality. However many controllers are not loaded on application start and thus I need to be able to intercept them right after they have been loaded (right after a specific view has been loaded for example) and run the modifications.

How can I achieve that, without changing any of the source files. All changes and listeners must be added from third party code.

Example code:

awesome.js:

awesomeApp.controller('AwesomeController', ['$scope', function($scope) {
  $scope.awesomeFunction = function...
}]);

punyIntegration.js

(function() {
  $rootScope.$on('awesomeControllerHasBeenLoaded', function(controller) {
    controller.scope.punyFunction = function...
  });
})();

By listening to the $viewContentLoaded event you can achieve such functionality. However to do this on any page and not on a specific view, you have to listen via the $rootScope like so:

$rootScope.$on("$viewContentLoaded", function($event, data) {
  //at this point the view has been loaded
  //and you have access to its scope (i.e the controller's scope)
  //via angular.element(any selector).scope()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM