如何正确地将Facebook JavaScript SDK注入AngularJS控制器?

Gal*_*aim 17 facebook-javascript-sdk angularjs

我是新来AnuglarJS并已经建立了一个小型web应用程序有了它,我想使用Facebook的JavaScript SDK它,但使用的最佳实践(依赖注入到控制器,以保持应用程序的结构和可测性).

我找到了这个https://groups.google.com/forum/#!msg/angular/bAVx58yJyLE/Kz56Rw-cQREJ, 但对于这个框架的新手(模块,服务和工厂没有很好地解释恕我直言),这非常令人困惑.

那么,在AngularJS应用程序中使用Facebook SDK的正确方法是什么?

Ben*_*esh 5

我实际上不得不这样做...我没有代码跟我一起,无论如何它可能都是专有的...但它基本上是这样的:

// 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();
       });
    };
});
Run Code Online (Sandbox Code Playgroud)

如果有任何错误让我知道,我会查找我的工作代码,看看我错过了什么.但这应该是关于它的.

  • 只是为了扩展@blesh的答案.查看这个更开发的示例:http://jsfiddle.net/bradbirdsall/ggmRQ/6/ (3认同)

hug*_*ige 5

2015年编辑!

这是一个古老的答案.我建议你查看github上流行的角度模块是如何做到的或者只是使用它们:

老答案

由于应用程序启动时调用的问题,我使用以下方法,该方法仅在加载SDK后加载应用程序:

window.fbAsyncInit = function () {
FB.init({
    appId: window.fbConfig.appID,
    channelUrl: '//' + window.location.hostname + window.location.pathname + 'channel.php',
    status: window.fbConfig.oInitOptions.bStatus || true,
    cookie: window.fbConfig.oInitOptions.bCookie || true,
    xfbml: window.fbConfig.oInitOptions.bXfbml || true
});


// Get Login Status once at init
window.FB.getLoginStatus(function (oResponse) {
    if (oResponse && oResponse.status) {
        window.fbConfig.sAuthStatus = oResponse.status;
    }

    // Bootstrap app here only after the sdk has been loaded
    angular.bootstrap(document.body, ['fbAngularApp']);
});
};

// 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/' + window.fbConfig.lng + '/all.js';
ref.parentNode.insertBefore(js, ref);
}(document));
Run Code Online (Sandbox Code Playgroud)