我想在我的 webapp 中创建动态页面标题。我创建了应该可以帮助我的服务,但它不起作用。PageTitleService.getTitle() 总是返回 undefined。有什么不对吗?运行此代码应该纠正什么?这是代码:
应用程序.js
var app = angular.module('app', ['restangular'])
.config(function ($routeProvider) {
$routeProvider.when('/index', {
templateUrl: 'views/main/index.html',
controller: 'PageController'
});
$routeProvider.when('/pages/:name', {
templateUrl: 'views/page/show.html',
controller: 'PageController'
});
$routeProvider.otherwise({
redirectTo: '/index'
});
});
app.defaultPageName = 'home';
app.name = 'Custom name';
PageTitleService.js:
app.factory('PageTitleService',
function() {
var title;
return {
setTitle : function(t) {
title = t;
},
getTitle : function() {
return title + ' - ' + app.name;
}
}
});
应用控制器.js
app.controller('AppController', ['$scope', 'PageTitleService',
function($scope, PageTitleService) {
$scope.pageTitle = PageTitleService.getTitle();
}]);
PageContorller.js
app.controller('PageController',
['$location', '$routeParams', '$scope', 'PageService', 'PageTitleService',
function($location, $routeParams, $scope, PageService, PageTitleService) {
var pageName = $routeParams.name !== undefined ? $routeParams.name : app.defaultPageName;
var page = PageService.getPage(pageName);
PageTitleService.setTitle(page.title); //page.title is always a string
$scope.title = page.title;
$scope.content = page.content;
}
]);
index.html(开始):
<!DOCTYPE html>
<html lang="en" data-ng-app="app" data-ng-controller="AppController">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<title>{{ pageTitle }}</title>
</head>