简体   繁体   English

从外部控制器加载控制器后,AngularJS添加回调

[英]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? 是否有可能在将控制器加载到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. 我正在将我们的应用程序与现有的angular应用程序集成在一起,并且我不想修改其源文件。 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: awesome.js:

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

punyIntegration.js punyIntegration.js

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

By listening to the $viewContentLoaded event you can achieve such functionality. 通过监听$viewContentLoaded事件,您可以实现这种功能。 However to do this on any page and not on a specific view, you have to listen via the $rootScope like so: 但是,要在任何页面上而不是在特定视图上执行此操作,都必须通过$rootScope进行监听,如下所示:

$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()
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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