1

I'm using facebook login am having trouble properly setting $scope.user. It is not being set automatically on the callback but only once I click something else on the page. I'm sure it's something simple I'm missing but could use some help.

My HTML

 <nav class="navbar navbar-default navbar-fixed-top" 
    role="navigation" ng-controller="HomeCtrl">
      <p class="navbar-text pull-right"> 
        {{ user.name }} 
      </p> 
      <button 
        class="btn btn-default navbar-btn navbar-right" 
        ng-hide="user"
        ng-click="login()">Log In With Facebook
      </button>
  </nav>

HomeCtrl:

 .controller('HomeCtrl', function($scope) {
    $scope.user;

    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    $scope.login = function() {
      FB.login(function(response) {
        if (response.status === 'connected') {
          FB.api('/me', function(response) {
            console.log(response);
            $scope.user = response;
          });
        } 
      }, {scope: 'public_profile,email,user_friends'} );
    }
  })

If I run console.log($scope.user) after I set it to the response, it seems as though $scope.user is being set, however, it's not reflected in the HTML until after another element is clicked.

2
  • 3
    This is one of the numerous $scope.$apply() related question i guess? Commented Sep 28, 2014 at 16:41
  • @PSL, yes. Leave an answer and I'll accept, thank you. Commented Sep 28, 2014 at 16:42

1 Answer 1

3

The facebook login callback is not executed by angular. So angular doesn't have any way to know that it modified the scope, and that it has to reevaluate the expressions used in the HTML page.

You thus need to tell angular that something has changed in the scope:

      FB.api('/me', function(response) {
        console.log(response);
        $scope.$apply(function() {
            $scope.user = response;
        });
      });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.