这是HTML(片段):
<div class="header" ng-controller="Header" ng-hide="hideHeader"></div>
<div class="page" ng-view></div>
.header
始终具有相同的控制器,而.page
则根据路由具有不同的控制器。
问题是在控制器中为当前 URL 设置了hideHeader
。
告诉Header
控制器当前路由的控制器已更改hideHeader
值的最佳方法是什么?
我不认为把它放在$routeScope
上是正确的方法。此外,大多数时候,标题是可见的,很少有页面想要隐藏它。
另一个想法是在config()
方法中设置该变量:
$routeProvider
.when('/',
{
templateUrl:'views/hello.html',
controller:'Hello',
hideHeader:true
});
但是,我不确定这是一种正确的"AngularJS"方法。
我的最佳选择是什么?
谢谢。
我倾向于服务,因为 Angular 团队声明"拥有两个想要访问相同数据的控制器是您想要服务的典型标志。 (他们提到这一点的地方之一是在他们的 Angular 最佳实践讨论中:http://www.youtube.com/watch?v=ZhfUv0spHCY)。 他们还讨论了服务是共享状态的正确位置(瘦控制器是"视图和服务之间的粘合剂")。
所以,像这样:
myApp.service('headerStatus', function () {
var hideHeader = true;
this.hideHeader = function() {
return hideHeader;
};
this.setHeader = function(visibility) {
hideHeader = visibility;
};
});
然后有很多方法可以绑定它,但这里有一个简单的方法:
myApp.controller('Header', function ($scope,headerStatus) {
$scope.hideHeader = headerStatus.hideHeader();
});
还有一点:http://jsfiddle.net/Yxbsg/1/
或者,您可以使用一个值:
myApp.value('headerStatus',true);
myApp.controller('Header', function ($scope,headerStatus) {
$scope.hideHeader = headerStatus;
});
您可以在标头控制器中侦听$locationChangeStart
或$locationChangeSuccess
事件,然后根据 url 中的更改将其隐藏。
http://docs.angularjs.org/api/ng.$location
来自 AngularJS API 文档
$locationChangeStart
Broadcasted before a URL will change. This change can be prevented by calling preventDefault method of the event. See ng.$rootScope.Scope#$on for more details about event object. Upon successful change $locationChangeSuccess is fired.
Type:
broadcast
Target:
root scope
Parameters
Param Type Details
angularEvent Object Synthetic event object.
newUrl: string New URL
oldUrl: (optional) string URL that was before it was changed.
编辑
angular.module('myApp',[]).config(['$routeProvider',function($routeProvider){
// application routes here
}).run(['$rootScope','$location',function($rootScope,$location){
$rootScope.$on('$locationChangeStart',function(evt,newPath,oldPath){
switch(newPath){
case '/some/path':
case '/some/other/path':
case '/some/more/paths':
$rootScope.$broadcast('header.hide');
break;
default:
$rootScope.$broadcast('header.show');
break;
}
});
}])
.controller('HeaderCtrlr',['$scope',function($scope){
$scope.hideFlag = false;
$scope.$on('header.hide',function(){
$scope.hideFlag = true;
});
$scope.$on('header.show',function(){
$scope.hideFlag = false;
});
}]);