Facebook 评论插件 Angularjs

2024-03-16

在我的 AngularJS 应用程序中添加 facebook 评论插件时,我遇到了一个奇怪的错误。 应用程序页面的简化结构是

<html ng-app="myapp">
<head>
 ...
</head>
<body>
<div>
...
</div>
<div ng-view></div>
...
</body>
</html>

带有fb评论框的页面被加载到ng-view中。包含fb评论框的页面结构如下

<div id="fb-comment-box>
 <div class="fb-comments" data-href="http://mydomain.com/page/{{ page.id }}" data-numposts="5" data-colorsheme="light"></div>
</div>

The page是来自控制器的 angularjs 范围变量。当我在浏览器中加载此页面并检查元素时。它显示了正确的页面 ID,即 data-href 是

data-href = "http://mydomain.com/page/2"

但在fb评论框下方,Facebook显示以下错误

警告:http://mydomain.com/page/%7B%7B%20page.id%7D%7D http://mydomain.com/page/%7B%7B%20page.id%7D%7D是 无法到达。

我可以看到 angularJS 作用域变量没有绑定。有谁知道如何解决这个问题?


这可能是因为 FB 功能在 Angular 能够更改之前就启动了data-href属性。

指令在这里似乎是一个不错的选择:

您基本上需要创建评论框afterAngular 可以提供正确的 URL。
因为这涉及到异步 DOM 操作,所以需要使用FB.XFBML.parse()让 FB 处理评论框data-href属性被改变。

该指令:

.directive('dynFbCommentBox', function () {
    function createHTML(href, numposts, colorscheme) {
        return '<div class="fb-comments" ' +
                       'data-href="' + href + '" ' +
                       'data-numposts="' + numposts + '" ' +
                       'data-colorsheme="' + colorscheme + '">' +
               '</div>';
    }

    return {
        restrict: 'A',
        scope: {},
        link: function postLink(scope, elem, attrs) {
            attrs.$observe('pageHref', function (newValue) {
                var href        = newValue;
                var numposts    = attrs.numposts    || 5;
                var colorscheme = attrs.colorscheme || 'light';

                elem.html(createHTML(href, numposts, colorscheme));
                FB.XFBML.parse(elem[0]);
            });
        }
    };
});

HTML:

<div id="fb-comment-box" dyn-fb-comment-box
        page-href="https://example.com/page/{{page.id}}"
        numposts="5"
        colorscheme="light">
</div>

NOTE:
The directive's scope will constantly watch for changes in the page-href attribute and update the comment-box. You can change this to suit your needs (e.g. also watch for changes in the other attributes or bind it once and stop watching).


另请参阅此简短的演示 http://jsfiddle.net/ExpertSystem/TLLFg/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Facebook 评论插件 Angularjs 的相关文章

随机推荐