从angularjs工厂的后端获取空模型,并在成功时更新控制器变量

时间:2014-04-07 11:39:26

标签: angularjs angularjs-scope

这是我的工厂,在我的工厂http电话中,我正在为我的用户变量分配值,但它没有更新我的控制器。

mainApp.factory('AccountFactory', ['$http', function ($http) {
                var User = {

                };

                function getLogOnModel() {
                    $http.get("http://localhost/mylocalspecial/Account/LogOn").then(function (data) {
                        User = data.data;
                        alert(JSON.stringify(data.data));
                        return data;
                    });
                }

                // Init model (or leave it for the controller to init it)
                getLogOnModel();

                return {
                    User: User,
                    getLogOnModel: getLogOnModel
                };

            }]);

这是我的控制器,你可以在我的控制器中看到我将工厂用户变量分配给$ scope.logOnModel,但我的控制器没有更新。

mainApp
        .controller('AccountController', ['$scope', 'AccountFactory',
            'AuthenticationServiceFactory'
            , function ($scope, AccountFactory,
                AuthenticationServiceFactory) {

                $scope.logOnModel = {};
                $scope.customerModel = {};

                $scope.logOnModel = AccountFactory.User;
                alert(JSON.stringify(AccountFactory.User));



            }]);

1 个答案:

答案 0 :(得分:2)

这就是:

// 1
var User = {};   // local User variable references new object: #obj1

// 2
return { 
    User: User   // AccountFactory.User references same object: #obj1
    ...
}

// 3
User = data.data;   // local User variables references new object: #obj2
                    // AccountFactory.User still references old object: #obj1
                    // $scope.logOnModel still references AccountFactory.User
                    //     a.k.a. old object: #obj1

解决方案1:

不要重新分配整个对象(User = <some_new_object>),只需重新分配其属性:

User.prop1 = data.data.prop1;
User.prop2 = data.data.prop2;
...

(如果属性超过一对,这很繁琐且容易出错。)


解决方案2:

您可以将整个服务分配给范围属性并从范围引用它。

mainApp.factory('AccountFactory', ['$http', function ($http) {
    var service = {};
    service.User = {};
    service.getLogOnModel = function () {
        $http.get("...").success(function (data) {
            service.User = data;
            alert(JSON.stringify(data));
        });
    };

    // Init model (or leave it for the controller to init it)
    service.getLogOnModel();

    return service;
}]);

mainApp.controller('AccountController', ['$scope', 'AccountFactory',
    function ($scope, AccountFactory) {
        $scope.account = AccountFactory;
        ...
    }
]);

// In HTML:
{{account.User.EmailAddress}}

另请参阅此 short demo