【问题标题】:Attribute binding not working on metadata属性绑定不适用于元数据
【发布时间】:2018-03-24 01:20:00
【问题描述】:

由于某种原因,我无法为 head 元素中的元素属性进行绑定。令人惊讶的是,相同的绑定确实适用于 head 元素中的元素。

我在下面粘贴了我正在使用的代码。 title 元素被正确绑定,但相同的绑定不适用于 meta property="og:title" 元素。我已经尝试过 content="{{ var }}" 和 ng-attr-content="{{ var }}"。谁能告诉我为什么会这样以及如何解决这个问题?

我在 chrome 开发者控制台中看到以下内容:

index.html:

<!DOCTYPE html>
<html ng-app="test">
  <head>
    <title ng-bind="documentTitle"></title>

    <meta property="og:title" ng-attr-content="{{ documentTitle }}" />
    <meta name="description" ng-if="documentDescription" ng-attr-content="{{ documentDescription }}" />
    <meta name="fragment" content="!">
    <meta name="prerender-status-code" ng-attr-content="{{statusCode}}">

    <base href="/" />

    {% include 'stylesheets.html' %}
  </head>

  <body>
    {% include 'javascripts.html' %}
  </body>
</html>

test.js:

function run($http, $locale, $rootScope, $route, Head) {
  $rootScope.$on('$routeChangeSuccess', function() {
    Head.setTitle($route.current.meta.title);
    Head.setDescription($route.current.meta.description);
    Head.setStatusCode('200');
  });
}

头部服务:

(function ($, _) {
  'use strict';

  angular
    .module('test.utils.services')
    .factory('Head', Head);

  Head.$inject = ['$rootScope'];

  function Head($rootScope) {
    var Head = {
      setStatusCode: setStatusCode,
      setTitle: setTitle,
      setDescription: setDescription
    };

    return Head;

    function setStatusCode(statusCode) {
      $rootScope.statusCode = statusCode;
    }

    function setTitle(title) {
      $rootScope.documentTitle = title;
    }

    function setDescription(description) {
      $rootScope.documentDescription = description;
    }
  }
})($, _);

【问题讨论】:

    标签: javascript html angularjs angularjs-scope


    【解决方案1】:

    把所有的头变量放在这样的对象中

    而不是$rootScope.statusCode = statusCode;

    输入$rootScope.head.statusCode = statusCode;

    然后在html中像这样使用

    &lt;meta property="og:title" ng-attr-content="{{ documentTitle }}" /&gt;

    &lt;meta property="og:title" ng-attr-content="{{ head.documentTitle }}" /&gt;

    组件之间不绑定字符串,只绑定对象

    【讨论】:

    • 也不起作用。我添加了 $rootScope.head = {};在 test.js 中添加 run() 的顶部,并在所有引用前加上 head。在开发人员控制台中显示相同的结果。尝试使用和不使用 ng-attr。将 title 元素绑定到 head.title 确实有效。
    • 你应该使用 content="{{ head.documentTitle }}" 或 ng-attr-content="head.documentTitle"
    • 啊,我当时试图 ng-attr 替代错误,但据我所见,它仍然无法正常工作。甚至 prerender.io 呈现的页面显示 或没有 ng-attr 。非常感谢您迄今为止的帮助,谢谢。
    【解决方案2】:

    我终于让它工作了。问题是 Django 以某种方式弄乱了模板。在 Django 不应该解析的部分周围加上 {% verbatim %} 和 {% endverbatim %} 后,问题就解决了。

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多