[英]Global “App” controllers in AngularJS
I have noticed in a few tutorials and code examples floating around the internet developers using a global AppController in their applications and modules. 我注意到在一些教程和代码示例中浮现在互联网开发人员的应用程序和模块中使用全局AppController。
Is it best practice to create a global AppController in AngularJS? 在AngularJS中创建全局AppController是最佳实践吗?
I do see some benefits such as being able to handle events in a "global" scope such as: 我确实看到了一些好处,例如能够在“全局”范围内处理事件,例如:
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 to this pattern? 这种模式还有其他优点或缺点吗?
Purely in context of situation. 纯粹是在情境的背景下。 Let's take an example of dynamically changing title tags and page view:
我们举一个动态更改标题标签和页面视图的示例:
.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 our title and page view are being dynamically loaded in through app level controller that wraps our application. 现在我们的标题和页面视图都通过包装我们的应用程序的应用程序级控制器动态加载。 This can be very useful.
这非常有用。
<html lang="en" ng-controller="app">
<head>
<title>{{title}}</title>
</head>
<body>
<ng-include src="page"></ng-include>
</body>
</html>
Here's an example of when not to use it. 这是一个不使用它的例子。 Let's say one of our partial pages return data from an API:
假设我们的某个部分页面从API返回数据:
<!-- search.html -->
<div ng-repeat="item in items">
{{item.title}}
</div>
And in our app level controller we are pulling data via broadcast: 在我们的应用级控制器中,我们通过广播提取数据:
$scope.$on('searchComplete',function(d){
$scope.items = d
});
That partial will show the data as we intended however - problems could arise when other child partials use items
where scope is being overwritten. 然而,部分将按照我们的意图显示数据 - 当其他子部分使用范围被覆盖的
items
,可能会出现问题。
<!-- other-search.html -->
<div ng-controller="OtherSearch" ng-click="search()">
<div ng-repeat="item in items">
{{item.title}}
</div>
</div>
In this partial, ng-click
is guiding the users request. 在此部分中,
ng-click
指导用户请求。 So if the app level controller already binded items
in the parent, the user will see a list of items when toggling to this partial even if they never triggered the action of search()
. 因此,如果应用级别控制器已经绑定了父级中的
items
,则用户在切换到此部分时将看到项目列表,即使它们从未触发过search()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.