2

一旦我听说了 Angular 并阅读了文档,就爱上了它。所以我阅读了 Angularjs 的 11 步教程,现在我正在尝试使用 Facebook SDK 构建一个应用程序。我的主题说明了一切,但我将进一步解释。

下面的代码,我在我的 html 视图/部分视图中有。我想将那段代码移动到服务或工厂模块。

  // Init the SDK upon load
   window.fbAsyncInit = function() {
     FB.init({
       appId      : 'APP_ID', // App ID
       channelUrl : 'channel.html', // Path to your Channel File
       status     : true, // check login status
       cookie     : true, // enable cookies to allow the server to access the session
       xfbml      : false  // parse XFBML
      });

     angular.bootstrap(document, ['myApp']);
   };

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

即使我当前的代码正在运行,我还是有点恼火,因为如果可能的话,我希望我的视图只包含 html 代码。我也认为这是一个最佳实践。:)。提前致谢。

4

2 回答 2

2

我将构建一个工厂,该工厂返回一个在加载 SDK 时已解决的承诺。就像是:

(function (window) {
    "use strict";

    var angular = window.angular;
    angular.module('facebookService', []).factory('FacebookService', [
    '$q','$rootScope', function ($q, $rootScope) {
        function init() {
            $rootScope.$apply(function () {
                defer.resolve();
            });
         }
         var defer = $q.defer();
         defer.promise.then(function () {
             // FB.Init...
            window.FB = 'Facebook SDK loaded'; // Remove this line
         });

         window.fbAsyncInit = angular.bind(this, init);

         return defer;
    }]);
}(window));

现在您可以使用在 pomise 上注入服务和附加方法FacebookService.promise.then(...)

这是一个示例http://jsfiddle.net/fredrik/f4tkA/

于 2013-08-07T08:06:10.897 回答
-1

You should look at the Angular seed project for good structuring practise:

https://github.com/angular/angular-seed

You could create it as a service (above) or you could have it run when your app loads once. If you need to reuse the code then build it as a service or directive:

angular.module('myApp',[])
       .run([ '$q','$rootScope', function ($q, $rootScope){
        }]);}

You can view a fiddle here but will have to enter you API keys for Facebook to get it to work.

于 2013-08-07T13:50:41.970 回答