Scope property doesn't update until page refresh

1.2k views Asked by At

I'm using resource in a factory to authenticate a user. I set $scope.user = User.user in my controller and print out user.username in my view. This all works like a champ except that I don't see the username until I refresh the page.

Here's my code simplified:

HTML

<div ng-app="app">
    <div ng-controller="MainCtrl">
        {{ user.username }}
    </div>
</div>

Controller

app.controller('MainCtrl', ['$scope', '$location', 'User',
function ($scope, $location, User) {
    $scope.user = User.user;

    $scope.login = function(username, password) {
        User.login({username:username, password:password},
        function(user) {
            $scope.user = user;
            $location.path('/');
        });
    }
}]);

Factory

app.factory('User', ['$resource', '$location', function($resource, $location) {
    var currentUser = {};
    return {
        login: function(user, success, error) {
            $resource('/login').save(
                user,
                function(resp) {
                    user.isLoggedin = true;
                    currentUser = user;
                    success(user);
                },
                function(resp) {
                    alert(resp.data.message.text);
                    error(user);
                }
            );
        },
        user: currentUser
    }
}]);
1

There are 1 answers

0
Justin Boyson On BEST ANSWER

Figured it out. Basically I was trying to alter scope in the factory. Here's the working code:

Factory:

arc.factory('User', ['$resource', function($resource) {
    return $resource('/users/:op/:id.json', {}, {
        login: { method:'POST', params:{ op:'login' } },
        logout: { method:'GET', params:{ op:'logout' } },
        getCurrentUser: { method:'GET', params:{ op:'getCurrentUser' } }
    });
}]);

Controller

arc.controller('MainCtrl', ['$scope', '$location', 'User',
    function ($scope, $location, User) {
        $scope.user = User.getCurrentUser();

        $scope.logout = function() {
            User.logout(
                function(response) {
                    $scope.user = response.user;
                    $location.path('/login');
                }
            );
        }
        $scope.login = function(username, password) {
            User.login({username:username, password:password},
            function(response) {
                $scope.user = response.user;
                $location.path('/');
            });
        }
    }]);

Now the view updates like it's supposed to.

{{ user.name }}