Domanda

I want to create dynamic page title in my webapp. I've created service which should helps me, but it does not work. PageTitleService.getTitle() always returns undefined. Is there someting wrong? What should be corected to run this code? Here is the code:

app.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;
        }
    }
});

AppController.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 (begin):

<!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>
È stato utile?

Soluzione

The line the AppController is run once.

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

After that, you can change title with setTitle('something') but $scope.pageTitle will still be undefined.

Instead, what you can do is:

$scope.getPageTitle = PageTitleService.getTitle;

Then in the view

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

To use it.

Altri suggerimenti

From my first impression I would suggest to try this:

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

        setTitle : function(t) {
            self.title = t;
        },
        getTitle : function() {
            self.title + ' - ' + app.name;
        }
    }
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top