Angular Dynamic meta tags in head

后端 未结 4 1978
再見小時候
再見小時候 2020-12-06 20:52

I need to insert open graph meta tags on a particular page in an angular app.

These tags are different based on the news or video that the page has.

I tried

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 21:19

    If you are using ui-router, you can use $stateChangeSuccess to set dynamically meta description and other meta tags based on current state. You have to put custom meta description in each state defined in $stateProvider.state(...).

    You must have in HTML markup, then and then document.getElementsByTagName('meta') will be able to return the meta description tag.

    $stateProvider
        .state('app.about', {
            url: 'about',
            templateUrl: '/modules/core/client/views/about.client.view.html',
            controller: 'AboutController',
            controllerAs: 'vm',
            metaDesc: 'Learn about my awesome social site.',
            data: {
                pageTitle: 'About | The Social Site'
            }
        })
    
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
    
        var metaDesc = $state.current.metaDesc || "Default Meta Description";
    
        var metas = document.getElementsByTagName('meta');
    
        for (let i = 0; i < metas.length; i++) {
            if (metas[i].getAttribute("name") === "description") {
                metas[i].setAttribute("content", metaDesc);
                break;
            }
        }
    });
    

提交回复
热议问题