2014-12-08 121 views
2

我試圖爲我的網站實現動態搜索引擎優化,其中涉及一些頁面的動態Meta描述。我嘗試了很多方法來獲取Meta描述,但無濟於事;我會看到在控制檯的元件相同的結果視圖:angularjs動態元描述拒絕顯示

<html lang="en" ng-controller="GlobalController"> 
    <head> 
     <meta name="fragment" content="!"> 
     <meta name="description" content="{{metaDescription}}"> 
    </head> 
    <body> 
     etc... 
    </body> 
</html> 

GlobalController

$scope.metaDescription = 'test description'; // Doesn't show in html 
console.log($scope.metaDescription); // shows in console 

Empty description screenshot

1)經由控制器

HTML設置元描述


2)使用$rootScope

HTML:

<meta name="description" content="{{metaDescription}}"> 

控制器:

$rootScope.metaDescription = 'test description'; // Doesn't show in html 
console.log($rootScope.metaDescription); // shows in console 

3)使用服務(基於https://weluse.de/blog/angularjs-seo-finally-a-piece-of-cake.html

HTML:

<meta name="description" content="{{ SEO.metaDescription() }}"> 

服務:

angular.module('core').service('SEO', function() { 
    var metaDescription = ''; 
    var metaKeywords = ''; 
    return { 
     metaDescription: function() { return metaDescription; }, 
     metaKeywords: function() { return metaKeywords; }, 
     reset: function() { 
      metaDescription = ''; 
      metaKeywords = ''; 
     }, 
     setMetaDescription: function(newMetaDescription) { 
      metaDescription = newMetaDescription; 
     }, 
     appendMetaKeywords: function(newKeywords) { 
      for (var key in newKeywords) { 
       if (metaKeywords === '') { 
        metaKeywords += newKeywords[key].name; 
       } else { 
        metaKeywords += ', ' + newKeywords[key].name; 
       } 
      } 
     } 
    }; 
}); 

控制器:

SEO.setMetaDescription('here is a test description'); // Doesn't show in html 
console.log(SEO.metaDescription()); // shows in console 

可能有人請您指出我的問題可能和解決方案?

+0

嗨,你有任何解決方案呢?我正在尋找相同的解決方案。謝謝 – 2015-01-16 11:32:17

回答

0

如果你正在寫直接在$ routeProvider的描述,你可能會設置這樣的:

App.js

myApp.config(function ($routeProvider, $locationProvider) { 
    $locationProvider.html5Mode(true); 
    $routeProvider 
     .when('/', { 
     title: 'Home page', 
     metaDescription: 'description of page home', 
     templateUrl: 'views/main.html', 
     controller: 'MainCtrl' 
     }) 
     .otherwise({ 
      redirectTo: '/' 
     }); 
    }); 

    myApp.run(['$location', '$rootScope', function($location, $rootScope,) { 
      $rootScope.$on('$routeChangeSuccess', function (event, current) { 

     $rootScope.metaDescription = current.$$route.metaDescription; 
      }); 
     }]); 

的Index.html

<meta name="description" content="{{metaDescription}}"> 

注意。在頁面編入索引之後編寫,以便Google抓取工具可以看到它們。