Angular Dynamic meta tags in head

后端 未结 4 1926
再見小時候
再見小時候 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:14

    I created an Angular module that can be used to set meta tags dynamically using the $routeProvider route definitions.

    angular.module('YourApp','ngMeta')
    .config(function ($routeProvider, ngMetaProvider) {
    
      $routeProvider
      .when('/home', {
        templateUrl: 'home-template.html',
        meta: {
          //Sets 'Home Page' as the title when /home is open
          title: 'Home page', 
          description: 'This is the description of the home page!'
        }
      })
      .when('/login', {
        templateUrl: 'login-template.html',
        meta: {
          //Sets 'Login Page' as the title when /login is open
          title: 'Login page',
          description: 'Login to this wonderful website!'
        }
      })
    });
    

    You can then set the meta tags in HTML like so

    
        
    
    
    
    
    
    
    
    
    
    
    

    To set the title, description and og:image dynamically, you can inject ngMeta into your controller

    .controller('DemoCtrl', function(ngMeta) {
    
        ngMeta.setTitle('Demo page');
        ngMeta.setDescription('This is the description of the demo page');
        ngMeta.setOgImgUrl('http://example.com/abc.jpg');
    });
    

    Support for more tags and ui-router are in the works.

提交回复
热议问题