× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Change the title of your AngularJS app as the user navigates each controller

Sebastian Sastre
Nov 21, 2014
<p>Here is a tip on how to keep nice titles in your <a href="http://en.wikipedia.org/wiki/AngularJS">AngularJS</a>-based <a href="http://en.wikipedia.org/wiki/Single-page_application">SPA - Single Page Application</a>.</p><p>The strategy is this:</p><ol><li>Remember current title (whatever it might be)</li><li>Set the title to whatever new value you want</li><li>Observe when the controller gets destroyed and</li><li>React restoring that previous value in the title</li></ol><pre><code class="language-javascript"> controllers.controller('AmazingDetailController', [ '$scope', '$window', function ($scope, $window){ // Sets this controller with the expected initial state // and perform any other initial activity needed $scope.initialize = function () { // Remember the previous title (whatever it might be) $scope.previousTitle = $window.document.title; $window.document.title = 'Amazing Detail!'; // Observes $destroy to restore the title of the page to its original // value once user navigates out of this controller $scope.$on('$destroy', function() { $window.document.title = $scope.previousTitle; }); }; // Does specific behavior 1 // Does specific behavior 2 // ... // Does specific behavior N $scope.initialize(); }]); </code></pre><p><span style="color:rgb(95, 99, 102); font-family:lato,sans-serif">A realistic </span>use will probably be use a model that is coming from a service from the backend (or cache) or collaborating with other objects somehow. But this strategy is still valid, clean and works like a charm.</p><p>Enjoy and let me know how it goes for you!</p>
comments powered by Disqus