Global App Controllers in AngularJS

I noticed in several tutorials and code examples floating around Internet developers using the global AppController in their applications and modules.

Is it best to create a global AppController in AngularJS?

I see some advantages, such as the ability to handle events in the "global" area, for example:

app.controller('AppController', function($scope, $rootScope, $route, $location){ $rootScope.$on('$routeChangeStart', function(event, current, previous) { console.log('Do something...'); }); $rootScope.$on('$routeChangeSuccess', function(event, current, previous) { console.log('Do something...); }); }); 

Are there any other advantages or disadvantages in this template?

+4
source share
1 answer

Purely in the context of the situation. Let's look at an example of dynamically changing title tags and pageviews:

 .config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider){ $routeProvider.when('/', { template: '/views/home.html', title:'Home' }); $locationProvider.html5Mode(true); }]); .controller('app', ['$scope','$route','$location',function($scope,$route,$location){ $scope.$on("$routeChangeSuccess",function($currentRoute,$previousRoute ){ $scope.title = $route.current.title; $scope.page = $route.current.template; }); }]); 

Now both headings and pageviews are dynamically loaded through the application level controller, which terminates our application. This can be very helpful.

 <html lang="en" ng-controller="app"> <head> <title>{{title}}</title> </head> <body> <ng-include src="page"></ng-include> </body> </html> 

Here is an example of when not to use it. Let's say one of our partial pages returns data from the API:

 <!-- search.html --> <div ng-repeat="item in items"> {{item.title}} </div> 

And in our application level controller, we pull the broadcast data:

 $scope.$on('searchComplete',function(d){ $scope.items = d }); 

Partial display of data, as we suggested, - problems can occur when other child parts use items , where the content area is overwritten.

 <!-- other-search.html --> <div ng-controller="OtherSearch" ng-click="search()"> <div ng-repeat="item in items"> {{item.title}} </div> </div> 

In this partial expression, ng-click directs a user request. Therefore, if the application-level controller is already attached to items in the parent, the user will see a list of items when switching to this partial, even if they never run the search() action.

+4
source

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


All Articles