how to properly inject Facebook JavaScript SDK to AngularJS controllers?

后端 未结 5 1793
一整个雨季
一整个雨季 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:44

    I was stumped on this for a while, I solved it with a $watch

    //setup watch for FB API to be ready
    //note that since you use $window, you need to inject it into your controller
    //angular.module('myApp').controller('appController', function ($scope, $window, ...) {
    $scope.FBListener = $scope.$watch(function () {
      return $window.FB;
    }, function (newVal, oldVal) {
      // FB API loaded, make calls
      console.log("FB is ready");
      //functions that do FB API calls
      $scope.getFBEvents();
      $scope.getFBPosts();
    });
    

    when FB has been loaded, you can clear the $watch (which is probably best to do for performance) by calling $scope.FBListener();

提交回复
热议问题