Facebook comment plugin Angularjs

I got a weird error when adding the facebook comment plugin in my AngularJS application. Simplified application page structure

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

The page with the fb comment field is loaded into ng-view. The page structure containing the fb comment block is as follows

 <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> 

page is the range variable of the angular variable that comes from the controller. When I load this page in a browser and check the item. It shows the correct page id, i.e. data-href

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

But below the comment field of fb, Facebook shows the following error

Warning: http://mydomain.com/page/%7B%7B%20page.id%7D%7D is unreachable.

I see that the angularJS scope variable is optional. Does anyone know how to solve this problem?

+4
source share
1 answer

This is probably due to the fact that the FB functionality begins before Angular can change the data-href attribute.

The directive seems to be a good choice here:

You basically need to create a comment block after Angular, which can provide the correct URL.
Since this is due to asynchronous manipulation of the DOM, you need to use FB.XFBML.parse() so that the FB processes the comment block after changing the data-href attribute.

Directive:

 .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> 

<sub> Note:
The scope of the directive will constantly monitor changes to the page-href attribute and update the comment block. You can change this according to your needs (for example, monitor changes to other attributes or bind them once and stop viewing). Sub>


See also this short demo .

+22
source

Source: https://habr.com/ru/post/1211093/