更改页面TITLE标记以匹配页面's AngularJS中的H1标签

Change page TITLE tag to match page's H1 tag in AngularJS

本文关键字:AngularJS H1 标签 中的 TITLE      更新时间:2023-09-26

如何根据AngularJS中页面的H1标记动态更改页面的标题标记。

我知道在jQuery中我可以做一些类似的事情:

var title = $('#content').find('h1').first().text();
if (title.length >= 1)
{
    document.title = 'My Site Name  |  ' + (title);
}
else {
    document.title = 'My Site Name';
}

在AngularJS中,完成相同任务的最佳方式是什么?

我宁愿不把它放在app.js中,因为对我来说,把内容(可能会改变)和代码混合在一起似乎是错误的。如果我在局部视图中编辑H1的文本,它需要自动更改标题

假设您想将标题绑定到静态h1内容,则可以使用以下指令:

var app = angular.module('bindTitle', []);
app.directive('bindTitle', ['$document', function($document) {
  return {
    restrict: 'A',
    link: function(scope, iElement) {
      $document[0].title += ' | ' + iElement.text();
    }
  };
}]);

用途为:

<html>
<head>
  <title>My Site Name</title>
<head>
<body>
  <h1 bind-title>Your title</h1>
</body>
</html>

并且Your title将在页面加载时被附加到页面标题。即My Site Name | Your title

编辑:在h1元素上自动附加标题

var app = angular.module('bindTitle', []);
app.directive('h1', ['$document', function($document) {
  return {
    restrict: 'E',
    link: function(scope, iElement) {
      $document[0].title += ' | ' + iElement.text();
    }
  };
}]);

<h1>元素中的内容将附加到页面标题中。

它在文档中,

试试这个

  angular.module('documentExample', [])
    .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
      $scope.title = $document[0].title;
      $scope.windowTitle = angular.element(window.document)[0].title;
    }]);

http://plnkr.co/edit/rlq032m5KTVLSRMDRHvr?p=preview

您可以将Angular在<title>元素上的数据绑定与ng-bindng-bind-template一起使用。

当然,您需要在模块/控制器上的变量(例如$scope)中具有所需的值才能使用数据绑定。如果该值不在范围内,Angular就无法提供比jQuery或标准JavaScript"更好"的解决方案(无论如何,您都需要在页面上找到<h1>标记并以某种方式提取文本)。

angular.module('app', [])
.controller('MyCtrl', function($scope) {
    $scope.title = 'My Page';
});
<html ng-app="app" ng-controller="MyCtrl">
<head>
<!-- Direct binding example -->
<title ng-bind="title"></title>
<!-- Or, template example -->
<title ng-bind-template="My Site{{ title.length > 0 ? ' | ' + title : ''}}"></title>

您可以使用$watch更改标题

<body ng-app="app">
    <div ng-controller="demo">
        <h1>{{title}}</h1>
        <input type="text" ng-model="title" />
    </div>
</body>
<script>
angular.module('app', []).controller('demo', ['$scope', function($scope) {
  $scope.$watch($scope.title, function() {
    document.title  = $scope.title;
  });
}]);
</script>

我认为最简单的方法是为您的标题和h1 设置相同的model

以这个jsFiddle链接为例。当您在该文本框中写入内容时,name会同时在两个位置进行修改。

注意:您应该在Layouthtml页面的MasterController中执行此操作。