samedi 25 avril 2015

Angularjs 1.3.15 - Updating $scope after Promise Returned


I'm learning angularjs and trying to update nav bar with user name after login, but the user name does not appear. Here is the process I am following:

  1. User logs in successfully.
  2. After 'then' in login promise (to make sure promise is returned), get user profile via factory which returns the user profile.
  3. After 'success' in getting user profile, save profile to $scope.user so that DOM is updated.

Here is HTML for Nav Bar (not sure if it matters but this is placed into index.html using ng-include on page load):

<nav ng-controller="menuController">
    <div class="navbar-header">
        <a class="navbar-brand" href="index.html">
            Admin Site
        </a>
    </div>
    <ul >
        <li ><span>Welcome {{ user.firstName }}</span></li>
    </ul>
  </div>
</nav>

Here is the menuController js file:

    angular
    .module('myApp')
    .controller("menuController", ['$scope', '$auth', '$timeout', '$window', 'toaster', 'Account',
        function UserCtrl($scope, $auth, $timeout, $window, toaster, Account) {

            $scope.user = [];

            $scope.login = function () {
                $auth.login({email: $scope.email, password: $scope.password})
                    .then(function(response){
                        toaster.pop('success', "Logged In", "You have successfully logged into the system"); // This fires correctly
                        Account.getProfile()
                            .success(function(obj){
                                $scope.user = obj;
                                console.log('User: ' + 
$scope.user.firstName);  //This Works! But user.firstName in HTML is not updated
                            });
                    })
                    .catch(function (response) {
                        toaster.pop('error', "Login Failure", response.data.message);
                    })
            };   
        }
    ]);

The problem is that the user.firstName in the navigation bar never updates with the user's first name. Am I missing something?

Thank you for any help!


Aucun commentaire:

Enregistrer un commentaire