1

我想在我的 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>
4

2 回答 2

0

该行AppController运行一次。

$scope.pageTitle = PageTitleService.getTitle();
// we didn't set title before, getTitle() returns undefined.

之后,您可以更改标题,setTitle('something')$scope.pageTitle仍将未定义。

相反,您可以做的是:

$scope.getPageTitle = PageTitleService.getTitle;

然后在视图中

<span ng-bind="getPageTitle()"></span>

使用它。

于 2013-08-28T11:01:32.557 回答
0

从我的第一印象来看,我建议试试这个:

app.factory('PageTitleService',
function() {
    this.title = "home";
    var self = this;
    return {

        setTitle : function(t) {
            self.title = t;
        },
        getTitle : function() {
            self.title + ' - ' + app.name;
        }
    }
});
于 2013-08-28T10:48:03.947 回答