1

Estoy creando una aplicación web de noticias con AngularJS, ya casi terminando me di cuenta que no le había dado mente a cómo iba a cambiar dinámicamente los meta tags sociales para Facebook y Twitter al acceder a cada ruta.

Los datos de las noticias están en archivos JSON y ahí mismo quería colocar los datos de los meta tags para la imagen, título, descripción, etc... de cada noticia. ¿Cómo podría implementar algo así?

1 respuesta 1

1

Aquí tienes un ejemplo espero te sirva https://github.com/jvandemo/angular-update-meta

Modo de uso:

Directiva: update-meta.js

// Create all modules and define dependencies to make sure they exist
// and are loaded in the correct order to satisfy dependency injection
// before all nested files are concatenated by Gulp

// Modules
angular.module('updateMeta', []);

(function(){

  /**
   * Update a meta tag dynamically
   *
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta
   *
   * @constructor
   */
  function UpdateMetaDirective($log) {

    function updateAttribute(selector, attributeName, attributeValue) {
      if(!document) {
        $log.error('updateMeta: document is not available!');
        return;
      }

      if (!selector) {
        $log.error('updateMeta: Either of "name", "httpEquiv", "property" or "charset" must be provided!');
        return;
      }

      var el = document.querySelector(selector);
      if (el && el.setAttribute) {
        el.setAttribute(attributeName, attributeValue);
      }
    }

    return {
      restrict: 'E',
      scope: {
        charset: '@',
        name: '@',
        content: '@',
        httpEquiv: '@',
        scheme: '@',
        property: '@',
        itemprop: '@'
      },
      link: function(scope, iElem, iAttrs) {
        var selector;

        if(scope.name) {
          selector = 'meta[name="' + scope.name + '"]';
        }

        if(scope.httpEquiv) {
          selector = 'meta[http-equiv="' + scope.httpEquiv + '"]';
        }

        if(scope.property) {
          selector = 'meta[property="' + scope.property + '"]';
        }

        if(scope.itemprop) {
          selector = 'meta[itemprop="' + scope.itemprop + '"]';
        }

        // watch the content parameter and set the changing value as needed
        scope.$watch('content', function (newValue, oldValue) {
          if (typeof newValue !== 'undefined') {
            updateAttribute(selector, 'content', scope.content);
          }
        });

        // watch the charset parameter and set it as needed
        scope.$watch('charset', function (newValue, oldValue) {
          if (typeof newValue !== 'undefined') {
            updateAttribute('meta[charset]', 'charset', scope.charset);
          }
        });
      }
    };
  }

  // Inject dependencies
  UpdateMetaDirective.$inject = ['$log'];

  // Export
  angular
    .module('updateMeta')
    .directive('updateMeta', UpdateMetaDirective);
})();

(function(){

  /**
   * Update a title dynamically
   *
   * @constructor
   */
  function UpdateTitleDirective($log) {

    return {
      restrict: 'E',
      scope: {
        title: '@'
      },
      link: function(scope, iElem, iAttrs) {

        // watch the value and set as needed
        // use document instead of $document as $document doesn't work here
        scope.$watch('title', function (newValue, oldValue) {
          if (typeof newValue !== 'undefined') {
            if(document){
              document.title = newValue;
            }
          }
        });
      }
    };
  }

  // Inject dependencies
  UpdateTitleDirective.$inject = ['$log'];

  // Export
  angular
    .module('updateMeta')
    .directive('updateTitle', UpdateTitleDirective);
})();

Html: index.html

<html ng-app="app">
<head>
  <script src="../bower/angular/angular.js"></script>
  <script src="../dist/update-meta.js"></script>
  <title>Initial static title</title>
  <meta charset="utf-8" />
  <meta http-equiv="Content-Language" content="en" />
  <meta name="description" content="Application wide description" />
  <meta property="og:title" content="The Rock" />
  <meta property="dynamicMeta" content="" />
  <meta itemprop="description" content="Application wide itemprop for Schema.org (Google+ uses this)">
  <script>
    var ngModule = angular.module('app', ['updateMeta']);
    ngModule.controller('AppController', function($scope, $timeout){
      $scope.dynamicMeta = "Initial value";
      $scope.dynamicTitle = "Initial dynamic value";
      $timeout(function(){
        $scope.dynamicMeta = "Value updated by timeout after 5 seconds";
        $scope.dynamicTitle = "Title updated by timeout after 5 seconds";
      }, 5000);
    });
  </script>
</head>
<body ng-controller="AppController">
  <update-meta charset="ISO-8859-1"></update-meta>
  <update-meta http-equiv="Content-Language" content="es"></update-meta>
  <update-meta name="description" content="A page specific description"></update-meta>
  <update-meta property="og:title" content="Minions"></update-meta>
  <update-meta property="dynamicMeta" content="{{ dynamicMeta }}"></update-meta>
  <update-title title="{{ dynamicTitle }}"></update-title>
  <update-meta itemprop="description" content="A page specific itemprop"></update-meta>
</body>
</html>
5
  • Deberías copiar las partes clave del enlace en tu respuesta. Si por cualquier motivo el enlace deja de funcionar, entonces esta respuesta dejará de tener sentido.
    – Alvaro Montoro
    el 17 may. 2016 a las 12:44
  • Gracias por la corrección saludos..!
    – vdjkelly
    el 17 may. 2016 a las 13:33
  • Eh colocado las etiquetas de los <update-meta> en el template de la ruta donde quiero que cambien los meta tags y me a funcionado correctamente, esa forma es la correcta de hacerlo ? el 18 may. 2016 a las 16:44
  • Si es la forma de hacerlo ya que el contenido actualizar proviene del controlador AppController.
    – vdjkelly
    el 23 may. 2016 a las 12:10
  • Saludos, los meta tags se actualizan correctamente y todo funciona bien pero al compartir un enlace en Facebook o Twitter por alguna razón los meta tags que selecciona son los principales que no están actualizados, qué crees que suceda? el 6 jun. 2016 a las 15:18

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.