从angularjs工厂的后端获取空模型,并在成功后更新控制器变量
这是我的工厂,在我的工厂http调用中,我给我的用户变量赋值,但它没有更新我的控制器从angularjs工厂的后端获取空模型,并在成功后更新控制器变量,angularjs,angularjs-scope,Angularjs,Angularjs Scope,这是我的工厂,在我的工厂http调用中,我给我的用户变量赋值,但它没有更新我的控制器 mainApp.factory('AccountFactory', ['$http', function ($http) { var User = { }; function getLogOnModel() { $http.get("http://localhost/myl
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
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=
),只需重新分配其属性:
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}}
另请参见,此解决方案2看起来不错,但在页面加载时不起作用。当我的页面加载电子邮件为空时,当我刷新页面时,我得到该值。我也观察到了同样的问题。我的要求是在页面加载时获取值..很抱歉让人头疼..A在年龄加载时加载数据。这只是调用获取数据的函数的一个步骤(就像我回答中的代码,它会立即调用
service.getLogOnModel();
)。非常感谢解决了我的问题,我喜欢解决方案2,因为我不必手动映射属性。现在,我只是从后端获取数据模型并为视图提供服务,我这样做的唯一原因是保持后端模型与前端同步。当做