Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Facebook JS SDK into AngularJS Controllers

I'm trying to create a facebook service for Angular so I can more easily test code that needs to use the Facebook JS SDK and Graph API for stuff.

Here's what I have so far:

app.factory('facebook', function() {
    return FB;
});

window.fbAsyncInit = function () {
    FB.init({
        appId: 'SOME_APP_ID_HERE', // App ID
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true,  // parse XFBML
        oauth: true
    });
};

// Load the SDK Asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
})(document);

Now, I know that the actual Facebook SDK part is working... but in my controller the reference is always null.

in my controller I just have something like this:

function FooCtrl($scope, facebook) {
    facebook.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
            // do something
        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook, 
            // but has not authenticated your app
        } else {
            // the user isn't logged in to Facebook.
        }
    });
}

Angular then gripes that it can't find a facebookProvider. Any ideas on how I can accomplish this?

like image 867
Ben Lesh Avatar asked Aug 19 '12 02:08

Ben Lesh


1 Answers

Enclose your factory function with array brackets like below

app.factory('facebook', [function() {
    return FB;
}]);

API docs are not clear enough. Point of having array brackets is that you can specify dependencies. It will be injected on creation of your service with AUTO.$inject. But since you don't have dependencies it will skip that task :)

Anyway, if you need dependencies you can request them like this

app.factory('facebook', ["$log", function($someCrazyLoggerService){
    $someCrazyLoggerService.log("I'm Auto Injected crazy Logger");
}]);
like image 113
Milan Jaric Avatar answered Nov 16 '22 02:11

Milan Jaric