我正在构建我的第一个AngularJS应用程序。
我希望在更改路径时动态地更改页面标题,因此我首先尝试将我的应用程序构建为:
<html ng-app>我想要一个页面级控制器,然后在它下面有子控制器。
所以,我一开始:
var app = angular.module("squareUpYourSavings", ["page1", "page2", "..."]);
app.controller('GlobalController', ['$scope', '$rootScope', function GlobalController($scope, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
$rootScope.$on("$locationChangeStart", function (event, nextLocation, currentLocation) {
console.log('nextLocation :: ' + nextLocation);
console.log('currentLocation :: ' + currentLocation);
});但这不管用。(不知道为什么)我有一个指向目录级控制器的导航器,ng视图可以工作,但是不会改变。$locationChange侦听器也不会触发。就好像这个顶级的控制器根本没有被听到。
因此,我更改了元素以指定顶级控制器:
<html id="ng-app" ng-controller="GlobalController">这一点现在起作用了,但这条路线似乎要发射两次。初始页面加载显示如下:
nextLocation :: location.html#/
currentLocation :: location.html#/ 然后,当我走到一条路线时,它正确地触发了前后,但当我到达那里时,它又触发了双火:
nextLocation :: location.html#savings-video // expected
currentLocation :: location.html#/ // expected
nextLocation :: location.html#/savings-video/ // not expected
currentLocation :: location.html#savings-video // not expected这是预期的行为吗?我做错了什么?
谢谢你,斯科特
发布于 2013-11-07 15:01:30
对于与整个应用程序相关的全局内容,而不是像标题这样的特定模块,我建议您将逻辑放在主控制器中:run模块方法:
var app = angular.module("squareUpYourSavings", ["page1", "page2", "..."]);
app.run(function($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
});哦,你应该离开你的路由器来决定哪个控制器在“控制”中:
<html ng-app> https://stackoverflow.com/questions/19838777
复制相似问题