AngularJS服务无法正常工作

时间:2013-08-28 10:38:02

标签: javascript angularjs angularjs-scope angular-services

我想在我的webapp中创建动态页面标题。我已经创建了应该帮助我的服务,但它不起作用。 PageTitleService.getTitle()始终返回undefined。有什么不对吗?应该如何运行此代码?这是代码:

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(开始):

<!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>

2 个答案:

答案 0 :(得分:0)

从我的第一印象中我建议尝试这个:

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

        setTitle : function(t) {
            self.title = t;
        },
        getTitle : function() {
            self.title + ' - ' + app.name;
        }
    }
});

答案 1 :(得分: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>

使用它。