【问题标题】:AngularJS trouble adding page titlesAngularJS 麻烦添加页面标题
【发布时间】:2015-07-16 03:26:42
【问题描述】:

我正在使用 AngularJS 编写一个网络应用程序。它不是一个单页应用程序,但我所有的代码都在一个文件 index.ejs 中。

所以我对 index.ejs 的设置大致如下:

<head>
   <title> Main page </title>
</head>
<body>
   <div class="row">
    <div class="col-md-10 col-md-offset-1">
       <ui-view></ui-view>
     </div>
   </div>

   <script type = "text/ng-template" id = "/main.html">
   .....
   </script>

   <script type = "text/ng-template" id = "/addStuff.html">
   .....
   </script>

   <script type = "text/ng-template" id = "/searchStuff.html">
   .....
   </script>

   <script type = "text/ng-template" id = "/about.html">
   .....
   </script>
</body>

我在 index.ejs 的顶部有一个主页的标题。我还想为每个页面设置单独的标题,这样当它们在新选项卡中打开时,我知道哪个是哪个。我试过这样做:

<script type = "text/ng-template" id = "/addStuff.html">
    <head>
        <title> Add Stuff </title>
    </head>
    .....

但这不起作用。有任何想法吗?谢谢。

【问题讨论】:

    标签: html angularjs uiview single-page-application angularjs-ng-template


    【解决方案1】:

    你应该使用 ui-router。在这种情况下,您可以在 bodyhtml 元素上添加顶级控制器,例如 &lt;html ng-app="my-app" ng-controller="AppCtrl"&gt;

    并在加载新路由时添加一个 '$stateChangeSuccess' 侦听器...

    .controller('AppCtrl', function AppCtrl($scope) {
    
        $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (angular.isDefined(toState.data.pageTitle)) {
                $scope.pageTitle = toState.data.pageTitle;
            }
        });
    })
    

    然后在路由定义中可以添加一个名为data.pageTitle的属性

        $stateProvider.state( 'profile', {
            url: '/profile',
            views: {
                "main": {
                    controller: 'ProfileCtrl',
                    templateUrl: 'profile/profile.tpl.html'
                }
            },
            data:{ 
               pageTitle: 'Profile' 
            }
        })
    

    然后在你的主index.html文件中,你可以绑定pageTitle属性:

        <title ng-bind="pageTitle"></title>
    

    【讨论】:

    【解决方案2】:

    最重要的部分是如果&lt;html&gt; 标记上不存在指令ng-app,则将其移动。

    因此所有的html页面都被angular覆盖了。

    例如:

    <html ng-app="app">
    
      ...
    
    </html>
    

    那么这真的是你的选择。
    您可以使用自定义指令来包装标题、生成服务或仅使用 {{ }} 语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      相关资源
      最近更新 更多