嗨,我有一个问题。
我的工厂中有一个对象如下
User: {
EmailAddress: ""
}
每当我进行 http 调用时,我都想更新返回值的 User.EmailAddress。在工厂内最好的方法是什么?这样在 Controller 级别我就可以将我的 $scope.Email 绑定(bind)到工厂变量。这就是我现在正在做的
GetLogOnModel: function () {
if ($location.path().indexOf("login") == 1) {
var promise = $http.get(config.headers.url + "LogOn").then(function (response) {
// The return value gets picked up by the then in the controller.
User.EmailAddress=response.data.Email;
return response.data
});
return promise;
// Return the promise to the controller
}
}
在 Controller 中
AccountFactory.GetLogOnModel().then(function (data) {
$scope.logOnModel = data;
}, function (err) {
console.log(err.reason);
alert(err.reason);
});
最佳答案
原始类型(如字符串)不受引用约束。所以你不能将范围属性绑定(bind)到 EmailAddress
直接并期望它自动更新。
另一方面,对象是通过引用绑定(bind)的,所以你可以这样做:
app.factory('AccountFactory', function (...) {
...
var User = {
...
EmailAddress: null
};
function getLogOnModel() {
$http.get(...).then(function (response) {
User.EmailAddress = response.data.Email;
});
}
// Init model (or leave it for the controller to init it)
getLogOnModel();
return {
...
User: User,
getLogOnModel: getLogOnModel
};
});
app.controller('someCtrl', function (..., AccountFactory) {
$scope.user = AccountFactory.User;
// Now you can reference `$scope.user.EmailAddress`
// and it will be kept in sync with `AccountFactory.User.EmailAddress`
});
关于angularjs - 在更新 Angular 工厂变量时更新 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906196/