Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to properly inject Facebook JavaScript SDK to AngularJS controllers?

I'm new to AnuglarJS and already built a small web-app with it, I would like to use the Facebook JavaScript SDK with it, but using best practices (dependency injecting to controllers, to maintain app structure and testability).

I found this https://groups.google.com/forum/#!msg/angular/bAVx58yJyLE/Kz56Rw-cQREJ but its very confusing for someone new to this framework (modules, services and factories are not explained well IMHO).

so, what is the proper way to use the Facebook SDK inside an AngularJS app ?

like image 793
Gal Ben-Haim Avatar asked Dec 10 '12 11:12

Gal Ben-Haim


People also ask

What is Facebook SDK for JavaScript?

The Facebook SDK for JavaScript provides a rich set of client-side functionality that: Enables you to use the Like Button and other Social Plugins on your site. Enables you to use Facebook Login to lower the barrier for people to sign up on your site. Makes it easy to call into Facebook's Graph API.


1 Answers

I have actually had to do this... I don't have the code with me, and it's probably proprietary anyhow... but it was essentially like this:

// create a simple factory:    
app.factory('facebook', ['$window', function($window) {

    //get FB from the global (window) variable.
    var FB = $window.FB;

    // gripe if it's not there.
    if(!FB) throw new Error('Facebook not loaded');

    //make sure FB is initialized.
    FB.init({
       appId : 'YOUR_APP_ID'
    });

    return {
        // a me function
        me: function(callback) {
            FB.api('/me', callback);
        }

        //TODO: Add any other functions you need here, login() for example.
    }
}]);

// then you can use it like so:
app.controller('SomeCtrl', function($scope, facebook) {

    //something to call on a click.
    $scope.testMe = function() {

       //call our service function.
       facebook.me(function(data) {
          $scope.facebookUser = data;

          //probably need to $apply() this when it returns.
          // since it's async.
          $scope.$apply();
       });
    };
});

If there are any errors in that let me know, and I'll look up the working code I have and see what I've missed. But that should be about it.

like image 54
Ben Lesh Avatar answered Oct 18 '22 19:10

Ben Lesh