如何正确实注入的JavaScript SDK来AngularJS控制器? [英] how to properly inject Facebook JavaScript SDK to AngularJS controllers?

查看:137
本文介绍了如何正确实注入的JavaScript SDK来AngularJS控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我发现这个<一个href=\"https://groups.google.com/forum/#!msg/angular/bAVx58yJyLE/Kz56Rw-cQREJ\">https://groups.google.com/forum/#!msg/angular/bAVx58yJyLE/Kz56Rw-cQREJ
但其新的人到这个框架非常混乱(模块,服务和工厂都没有很好地解释恕我直言)。

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

那么,什么是使用Facebook SDK的应用AngularJS内的正确方法?

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

推荐答案

其实我也不得不这样做......我没有code。与我,这可能是专有的,无论如何...但它基本上是这样的:

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

如果有任何错误在让我知道,我会查找工作code我,看看我已经错过了。但是,这应该是它。

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.

这篇关于如何正确实注入的JavaScript SDK来AngularJS控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆