How to dynamically change header based on AngularJS partial view?

后端 未结 22 1992
一向
一向 2020-11-22 10:53

I am using ng-view to include AngularJS partial views, and I want to update the page title and h1 header tags based on the included view. These are out of scope of the parti

22条回答
  •  心在旅途
    2020-11-22 11:42

    While others may have better methods, I was able to use $rootScope in my controllers, as each of my views/templates has a distinct controller. You will need to inject the $rootScope in each controller. While this may not be ideal, it is functioning for me, so I thought I should pass it along. If you inspect the page, it adds the ng-binding to the title tag.

    Example Controller:

    myapp.controller('loginPage', ['$scope', '$rootScope', function ($scope, $rootScope) {
    
    // Dynamic Page Title and Description
    $rootScope.pageTitle = 'Login to Vote';
    $rootScope.pageDescription = 'This page requires you to login';
    }]);
    

    Example Index.html header:

    
    
    
    
    
    {{pageTitle}}
    

    You can also set the pageTitle and pageDescription to dynamic values, such as returning data from a REST call:

        $scope.article = restCallSingleArticle.get({ articleID: $routeParams.articleID }, function() {
        // Dynamic Page Title and Description
        $rootScope.pageTitle = $scope.article.articletitle;
        $rootScope.pageDescription = $scope.article.articledescription;
    });
    

    Again, others may have better ideas on how to approach this, but since I am using a pre-rendering, my needs are being met.

提交回复
热议问题