在用户搜索事件中动态更改 AngularJS 应用文档标题
Dynamically Change AngularJS App Document Title on User Search Event
我正在 AngularJS 教程应用程序中实现搜索功能。因此,每当用户在搜索 <input>
字段中键入内容时,我都想更改文档的 <title>
.
为此,我在我的文档 <title>
中使用 query
模型和 ng-bind-template
以避免应用程序加载时双花括号 {{}}
闪烁效果。
以下是我的代码供参考。
<!DOCTYPE html>
<html lang="en" ng-app="phonecatApp" ng-controller="PhoneListCtrl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="icon" href="/assets/img/fav.png">
<title ng-bind-template="Phonecat | {{query}}">Phonecat</title>
<link rel="stylesheet" href="/assets/css/app.css">
<script src="/assets/js/angular/angular.min.js"></script>
</head>
<body>
<div>
<span>Search: </span><input ng-model="query" />
</div>
<ul>
<li ng-repeat="phone in phones | filter:query">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
</ul>
<p>Total number of phones: {{phones.length}}</p>
<script src="/assets/js/app.js"></script>
</body>
</html>
在这里,我的 <title>
标签有 ng-bind-template
指令和 query
模型和 pre-defined 内容,
Phonecat
现在,当页面加载文档时 <title>
设置为,
Phonecat |
而不只是“Phonecat”。
如果 query
模型是 EMPTY,我不想 ng-bind-template
评估和更改文档的 <title>
。如果 query
模型是 EMPTY,它应该只显示初始内容(Phonecat 在这种情况下)作为文档的标题 & 当 query
模型已更新且 NOT EMPTY,它应该更新标题(即 Phonecat | nexus mobile)。
如果有人能解释如何解决这个问题,那就太好了。
谢谢!
您可以在ng-binding
中使用三元运算符来有条件地构建标题:
<title ng-bind="query ? 'Phonecat | ' + query : 'Phonecat'">Phonecat</title>
或者:
<title>{{ query ? 'Phonecat | ' + query : 'Phonecat'}}</title>
我正在 AngularJS 教程应用程序中实现搜索功能。因此,每当用户在搜索 <input>
字段中键入内容时,我都想更改文档的 <title>
.
为此,我在我的文档 <title>
中使用 query
模型和 ng-bind-template
以避免应用程序加载时双花括号 {{}}
闪烁效果。
以下是我的代码供参考。
<!DOCTYPE html>
<html lang="en" ng-app="phonecatApp" ng-controller="PhoneListCtrl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="icon" href="/assets/img/fav.png">
<title ng-bind-template="Phonecat | {{query}}">Phonecat</title>
<link rel="stylesheet" href="/assets/css/app.css">
<script src="/assets/js/angular/angular.min.js"></script>
</head>
<body>
<div>
<span>Search: </span><input ng-model="query" />
</div>
<ul>
<li ng-repeat="phone in phones | filter:query">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
</ul>
<p>Total number of phones: {{phones.length}}</p>
<script src="/assets/js/app.js"></script>
</body>
</html>
在这里,我的 <title>
标签有 ng-bind-template
指令和 query
模型和 pre-defined 内容,
Phonecat
现在,当页面加载文档时 <title>
设置为,
Phonecat |
而不只是“Phonecat”。
如果 query
模型是 EMPTY,我不想 ng-bind-template
评估和更改文档的 <title>
。如果 query
模型是 EMPTY,它应该只显示初始内容(Phonecat 在这种情况下)作为文档的标题 & 当 query
模型已更新且 NOT EMPTY,它应该更新标题(即 Phonecat | nexus mobile)。
如果有人能解释如何解决这个问题,那就太好了。
谢谢!
您可以在ng-binding
中使用三元运算符来有条件地构建标题:
<title ng-bind="query ? 'Phonecat | ' + query : 'Phonecat'">Phonecat</title>
或者:
<title>{{ query ? 'Phonecat | ' + query : 'Phonecat'}}</title>