AngularJS app上的动态页面标题

时间:2014-07-09 06:01:35

标签: javascript node.js angularjs

我们正在构建一个大的AngularJS / NodeJS应用程序,我们遇到了一个问题。它与页面标题有关。在我们的应用程序中,我们希望为每个州提供动态页面标题(我们使用的是ui-router)。我知道我们可以将自定义字段添加到任何状态(如pageTitle):

.state('app.home', {
    url: "",
    templateUrl: '/templates/home.html',
    controller: 'HomeController',
    pageTitle: "Home"
})

然后我们可以在$stateChangeSuccess上检索该内容并将其设置为$scope

.run([
    '$rootScope', function ($rootScope) {
      'use strict';

      $rootScope.appState = $rootScope.appState || {};

      $rootScope.$on("$stateChangeSuccess", function (event, toState, toParams, fromState, fromParams) {

      //TODO: We need to update the title and meta here, and then retrieve it and assign it to appState
      $rootScope.appState.pageTitle = toState.pageTitle;

});

}]);

,然后在我们的index.html上执行:

<title ng-bind="appState.pageTitle">Page Title before the dynamic title kicks in</title>

但是,在我们的例子中,页面标题必须来自DB,通过调用我们的Node.js REST API。例如,想象一下,你去产品页面,你必须得到产品,获得产品的标题来设置页面标题。我们怎么能这样做?

干杯,
伊拿克里斯

1 个答案:

答案 0 :(得分:1)

您应该可以使用$document服务。

像:

function SampleController($document) {
    $document.title = "Updated from Angular.JS";
}

官方文件:

https://docs.angularjs.org/api/ng/service/$document