how to properly inject Facebook JavaScript SDK to AngularJS controllers?

后端 未结 5 1881
一整个雨季
一整个雨季 2021-02-02 14:01

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 contr

5条回答
  •  青春惊慌失措
    2021-02-02 14:45

    2015 EDIT !

    This is an old answer. I'll suggest you check out how the popular angular-modules on github do it or simply use them:

    • https://github.com/Ciul/angular-facebook
    • https://github.com/pc035860/angular-easyfb
    • https://github.com/GoDisco/ngFacebook

    Old Answer

    Because of problems with calls at the start of the app I use the following approach, which loads the app only after the SDK has been loaded:

    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));
    

提交回复
热议问题