范围属性在页面刷新之前不会更新

时间:2013-12-12 20:28:57

标签: angularjs angularjs-scope angularjs-resource

我正在工厂中使用资源来验证用户身份。我在控制器中设置了$scope.user = User.user,并在我的视图中打印出user.username。这一切都像冠军一样,只是在我刷新页面之前我没有看到用户名。

这是我的代码简化:

HTML

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

控制器

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('/');
        });
    }
}]);

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 个答案:

答案 0 :(得分:0)

想出来。基本上我试图改变工厂的范围。这是工作代码:

厂:

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' } }
    });
}]);

控制器

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('/');
            });
        }
    }]);

现在视图更新了它的预期。

{{ user.name }}