and here's the output" /> and here's the output" /> and here's the output"/>

ng-bind for title tag goes outside of the element

224 Views Asked by At

ng-bind used for the title tag inside the header behaves weird. This is my code:

<title page-title ng-bind="page_title"></title>

and here's the output:

My Page Sucks
<title page-title="" ng-bind="page_title" class="ng-binding"></title>

it goes outside instead of inside the title tag

here's a snippet of the pageTitle directive:

streamViewApp
// page title
.directive('pageTitle', [
    '$rootScope',
    '$timeout',
    function($rootScope, $timeout) {
        return {
            restrict: 'A',
            link: function() {
                var listener = function(event, toState) {

                    var name = ($rootScope.site_settings) ? (($rootScope.site_settings[0] != undefined) ? $rootScope.site_settings[0]  : 'StreamView' ): 'StreamView';

                    var default_title = name.value;

                    $timeout(function() {
                        $rootScope.page_title = (toState.data && toState.data.pageTitle)
                            ? default_title + ' - ' + toState.data.pageTitle : default_title;
                    });
                };
                $rootScope.$on('$stateChangeSuccess', listener);
            }
        }
    }
]);

UPDATE:

Works well when called within the body tag, weird thing happens when called in head

<body><title page-title="" ng-bind="page_title" class="ng-binding">My Page Sucks</title>
1

There are 1 best solutions below

1
Navoneel Talukdar On

Instead of using ng-bind define the pagetitle as custom data with router state.

state('customerdata', {
        url: '/viewcustomer',
        templateUrl: '/components/customers.html',
        controller: 'customerdatacntrl',
        controllerAs: 'self',
        data: {
            pageTitle: 'Customer Data'     <--- Notice here
        } 

Then in directive you can get hold of toState object and set the next page title from there.

return {
      link: function (scope, element) {    
        var listener = function (event, toState) {

          var pageTitle;
          if (toState.data && toState.data.pageTitle) {
            pageTitle = toState.data.pageTitle;
          }

          $timeout(function () {
            element.text(pageTitle);
          }, 0, false);
        };

        $rootScope.$on('$stateChangeSuccess', listener);
      }
};