Monday, September 9, 2019

Controller based title change with Angular

Here is a tip on how to keep nice titles in your AngularJS-based SPA - Single Page Application.
The strategy is this:
  1. Remember current title (whatever it might be)
  2. Set the title to whatever new value you want
  3. Observe when the controller gets destroyed and
  4. React restoring that previous value in the title
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();
    }]);
A realistic 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.
Enjoy and let me know how it goes for you!

No comments:

Post a Comment