Changing the page title dynamically is an important feature in our AngularJS WordPress Theme. If you have checked some articles related to this topic, you might find it’s a bit hard to integrate those methods to our theme. There are two reasons:
-
We just moved the
ng-app="app"
fromhtml
to#page
div, that means thetitle
element is beyond the scope of ourapp
. Most of the tutorials use the$scope.title
approach to change page title, unfortunately it won’t work with our theme. -
Most tutorials will predefine a title for each route, for example there are 3 files
a.html
,b.html
andc.html
, and their titles are likePage A
,Page B
andPage C
. In such scenario it’s much easier to get and set the page title on$routeChangeSuccess
event. But our case is a bit different that we’ll need to get a post from WP API first to know what the title is.
This post from stackoverflow gave me an idea to change the title with the global variable document
. Here’s the snippet I use to change the page title dynamically (line 7, line 14).
Note that I use document.querySelector('title').innerHTML
rather than document.title
, so special characters like HTML entities won’t be decoded. You can get full project files from the GitHub repo.
If you have any question related to my AngularJS WordPress theme series, just leave a comment here, I’ll get back to you as soon as I can.
Leave a Reply