Igor Simic
4 years ago

How to add Facebook comments to AngularJS directive




Facebook comments app are pretty nice and easy way to insert comments for your pages.In this example we will use Facebook comments in directive. Directive will load/reload FB comments on every page change.

To implement FB comments in Angular you have to first create FB Comment App, go to Facebook Developers page  and create your app. Once you are finished, you will get FB App code with your Comment App ID.

Now we can create directive to load FB JS SDK and load ads:
app.directive('fbComments', ['$timeout',function($timeout) {
	   
	  
	    return {
			 
			restrict: 'AE',      
			// Text Binding (Prefix: @)
			// One-way Binding (Prefix: &)
			// Two-way Binding (Prefix: =)
			scope: {
			href: '@href',
			numpost : '@numpost',
			colorscheme: '@colorscheme',
			order: '@order',
			width: '@width'
			},
			template: '<div class="fb-comments" '+
			              'data-href="{{href}}" '+
			              'data-numposts="{{numpost}}" '+
			              'data-colorscheme="{{colorscheme}}" '+
			              'data-order-by="{{order}}" '+
			              'data-width="{{width}}"> '+
			        '</div>',
			link: function($scope,element,attr){


				console.log("attr");
				console.log(attr);
 	
				window.fbAsyncInit = function() {

					console.log("FB init");
				    FB.init({
 				      appId            : 'YOUR_FB_COMMENTS_APP_ID',// here you can insert your FB Comments App ID
				      autoLogAppEvents : true,
				      xfbml            : true,
				      version          : 'v2.12'
				    });
				};

				(function(d, s, id){
				 var js, fjs = d.getElementsByTagName(s)[0];
				 if (d.getElementById(id)) {return;}
				 js = d.createElement(s); js.id = id;
				 js.src = "https://connect.facebook.net/en_US/sdk.js";
				 fjs.parentNode.insertBefore(js, fjs);
				}(document, 'script', 'facebook-jssdk'));
				

				function setComment() {
			        console.log("fb comments triggrered");

			        if (typeof FB != 'undefined' && FB !== null){ 
			        	console.log("retrigger FB");
	                    FB.XFBML.parse(element[0]);
	                  }
			
			    }

				$timeout(function(){ 
				    return setComment();
				});
 
 			}

	    };
	}]);

And now in your HTML document you can use this directive like this:
<fb-comments href="{{link_of_current_page}}"
                numposts="5"
                colorscheme="light"
                order=""
                width="100%">
            </fb-comments> 

And there you have it.


Thank you, 
and thank me :)