How to dynamically change header based on AngularJS partial view?

后端 未结 22 2244
一向
一向 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:19

    A clean way that allow dynamically setting title or meta description. In example I use ui-router but you can use ngRoute in same way.

    var myApp = angular.module('myApp', ['ui.router'])
    
    myApp.config(
        ['$stateProvider', function($stateProvider) {
            $stateProvider.state('product', {
                url: '/product/{id}',
                templateUrl: 'views/product.html',
                resolve: {
                    meta: ['$rootScope', '$stateParams', function ($rootScope, $stateParams) {
                        var title = "Product " + $stateParams.id,
                            description = "Product " + $stateParams.id;
                        $rootScope.meta = {title: title, description: description};
                    }]
    
                    // Or using server side title and description
                    meta: ['$rootScope', '$stateParams', '$http', function ($rootScope, $stateParams, $http) {
                        return $http({method: 'GET', url: 'api/product/ + $stateParams.id'})
                            .then (function (product) {
                                $rootScope.meta = {title: product.title, description: product.description};
                            });
                    }]
    
                }
                controller: 'ProductController'
            });
        }]);
    

    HTML:

    
    
    
        myApp
    ...
    

提交回复
热议问题