如何在angularjs中制作动态元描述?

时间:2015-05-04 21:03:01

标签: javascript angularjs

如何将Arraycontroller中的描述呈现给索引上的<meta name="description" content="{{metadescription}}">。 html,可以动态显示在视图

我使用$routeParams;当我把:title: ':pageName'标题替换为当前路线时,访问该页面。我需要在metadescription中执行类似的操作,使控制器items 中的数组NatureCtrl内的描述出现在视图中

控制器

angular.module('tareasApp')
  .controller('NatureCtrl', function ($scope, $routeParams, $sce, $location, $anchorScroll) { 

    $scope.pageName = $routeParams.pageName;

$scope.items =[
 {    
      href:'/relaxing-sounds-waves', 
      img:'waves.jpg', 
      description:'Those Relaxing Sounds of Waves'
 },
 {    
      href:'/relaxing-ocean-sounds', 
      img:'ocean.jpg', 
      description:'Nature Sounds Relaxing Ocean Sounds'
 }
];
 });

app.js

     var myApp = angular.module('tareasApp')
          myApp.config(function ($routeProvider, $locationProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider
              .when('/:pageName', {
                        templateUrl: 'views/wizard.html',
                        title: ':pageName',
                        metadescription: '',
                        controller: 'NatureCtrl'
                    })
                    .otherwise({
                      redirectTo: '/'
                    });
                });

    // That way I can get page titles based on the route and routeParams.
   //How do I set the $rootScope.metadescription for a description concerning each page?

    myApp.run(['$location', '$rootScope', '$routeParams', function($location, $rootScope, $routeParams) {
       $rootScope.$on('$routeChangeSuccess', function (event, current) {
       var title = current.$$route.title;
    if (title && $routeParams){
        for(var PageName in $routeParams) {
            title = title.replace(new RegExp(':' + PageName, 'g'), $routeParams[PageName]);
        }
    }
    $rootScope.title = title;
    $rootScope.metadescription = current.$$route.metadescription;
         });
     }]);

Page index.html

<!DOCTYPE html>
<html lang="pt-BR" ng-app="tareasApp">
<head>
<meta charset="utf-8">
<title ng-bind="title"></title>
<meta name="description" content="{{metadescription}}">
<base href="/">
<meta name="fragment" content="!">
</head>

<body>
   Content goes here... the views are injected here...
</body>
</html>  

编辑:

关键点是:如何为myApp.run配置metadescription可以与标题类似?

myApp.run(['$location', '$rootScope', '$routeParams', function($location, $rootScope, $routeParams) {
           $rootScope.$on('$routeChangeSuccess', function (event, current) {
           var metadescription = current.$$route.metadescription;
        if (metadescription && <!-- What I put here?-->){
            for(var PageDesc in <!-- What I put here?-->) {
                metadescription = metadescription.replace(new RegExp(':' + PageDesc, 'g'), <!-- What I put here?-->[PageDesc]);
            }
        }
        $rootScope.metadescription = metadescription;
             });
         }]);

0 个答案:

没有答案