A Facebook Share component for AngularJS

There are several facebook share components available for AngularJS however I was needing something that could:

  • Show a count of the number of shares
  • Work within the translation infrastructure of my app (ie a custom template)
  • Handle different URL mappings for pages – whilst a typical angular url might be http://app.com/#/path/… facebook can’t scrape this unless you use the #! method or somesuch. Because of this typically on the server we map to different links such as http://app.com/landing/path/…

The below code snippets work together to do all of this in a few lines:

angularApp.directive("ngFbShare", function($http, $rootScope) {
    return {
        restrict: 'A',
        templateUrl: 'views/components/fbshare.html',
        scope: {
            ngFbShare: "@",
        },
        link: function(scope, elem, attrs) {
            var link; // always the latest link relative to the base of the server. Use this for click tracking etc
            var update_share_link = function() {
                link = '/landing/' + scope.ngFbShare;
                scope.share_link = MY_FULL_ADDRESS + link;
            };
            update_share_link();
            scope.$watch('ngFbShare', update_share_link);

            scope.fb_total_count = 0;
            $http.get('http://api.facebook.com/method/links.getStats?format=json&urls=' + scope.share_link)
                .then(function(res) {
                    scope.fb_total_count = res.data[0].total_count;
                });                
        }       
    };      
});             

<a href="http://www.facebook.com/sharer/sharer.php?u={{ share_link }}" target="fb_share_window" class="btn btn-primary btn-fb">
    <i class="fa fa-fw fa-facebook"></i> Share
    <span class="count">{{ fb_total_count }}</span>
</a>

Leave a Reply

Your email address will not be published. Required fields are marked *