javascript - Angularjs 1.3.15 - Updating $scope after Promise Returned -
i'm learning angularjs , trying update nav bar user name after login, user name not appear. here process following:
- user logs in successfully.
- after 'then' in login promise (to make sure promise returned), user profile via factory returns user profile.
- after 'success' in getting user profile, save profile $scope.user dom updated.
here html nav bar (not sure if matters placed 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 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 logged system"); // fires correctly account.getprofile() .success(function(obj){ $scope.user = obj; console.log('user: ' + $scope.user.firstname); //this works! user.firstname in html not updated }); }) .catch(function (response) { toaster.pop('error', "login failure", response.data.message); }) }; } ]);
html index.html
<div id="wrapper"> <div ng-include='"templates/navigation.html"'></div> <div ng-view></div> </div> <!-- /#wrapper -->
the problem user.firstname in navigation bar never updates user's first name. missing something?
thank help!
what account.getprofile()
return? angular promise or outside angular framework? perhaps should wrap code inside $apply
scope:
account.getprofile() .success(function(obj){ $scope.$apply(function() { $scope.user = obj; console.log('user: ' + $scope.user.firstname); //this works! user.firstname in html not updated }); });
Comments
Post a Comment