📜 ⬆️ ⬇️

AngularJS: we configure event of initialization

If you already know what AngularJS is and use it for a long time, you probably already had the task to perform certain actions immediately after the application was initialized. And after reading the documentation, you find that there is no such way out of the box)

Of course, many of you will remember the run () method inside each module. However, I will answer you that this method works BEFORE the application is initialized. More precisely after the injector has loaded all the modules, but before they are executed. It is easy to check.

angular.module("use", []) .config([function(){ console.log("::use::config"); }]) .run([function(){ console.log("::use::run"); }]) .controller("BarCtrl", ["$scope", function($scope){ console.log("::use::ctrl::BarCtrl"); $scope.foo = "bar"; }]) ; 

The above code will output to the console:

 ::use::config ::use::run ::use::ctrl::BarCtrl 

Living example.
')
And yet there is a way to notify the application about initialization. The angular.bootstrap method will help us with this. This method allows you to attach a module to a DOM element without using the ng-app directive. After we attach the module and work out all the elements in it, we can get a link to the $ rootScope module from the injector and notify all child elements. In AngularJS there are 2 methods of working with events - $ emit and $ broadcast . The difference between the first and the second is that it works upward and can be stopped by any parent handler. In general, a direct analogue of DOM events. The second notifies "down" and it can not be stopped. Both methods start with the current scope.

So, let's try to summarize all the arguments and show this piece of code already.

 angular.element(document).ready(function(){ var $inj = angular.bootstrap(document.body, ['use']); var $rootScope = $inj.get("$rootScope"); $rootScope.$broadcast("init", "hello"); $rootScope.$digest(); }); 

Living example

Since we are outside the context of AngularJS, we need to run the internal $ digest () loop ourselves. As can be seen from the console from the example at the link above, the event starts exactly after the operation of all the components of the module. What, actually, was required.

Source: https://habr.com/ru/post/232219/


All Articles