krishnaxv krishnaxv - 6 months ago 24
AngularJS Question

Dynamically Change AngularJS App Document Title on User Search Event

I am implementing a Search feature in my AngularJS tutorial application. So, whenever a user types in the Search

<input>
field, I want to change my document's
<title>
.

For this, I am using
query
model with
ng-bind-template
in my document's
<title>
to avoid double curly braces
{{}}
flicker effect when application loads.

Following is my code for reference.

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


Here, my
<title>
tag has
ng-bind-template
directive with
query
model & pre-defined content,


Phonecat


Now, when page loads document
<title>
is set to,


Phonecat |


Instead of just "Phonecat".

I don't want
ng-bind-template
to evaluate & change my document's
<title>
if
query
model is EMPTY. If
query
model is EMPTY, it should just display the initial content (Phonecat in this case) as document's Title & when the
query
model is updated & NOT EMPTY, it should update the Title (i.e. Phonecat | nexus mobile).

It will be great if someone can explain how to approach this.

Thanks!

Answer

You can use the ternary operator inside ng-binding to conditionally build the title:

<title ng-bind="query ? 'Phonecat | ' + query : 'Phonecat'">Phonecat</title>

Alternatively:

<title>{{ query ? 'Phonecat | ' + query : 'Phonecat'}}</title>
Comments