我有一个AngularJS应用程序,我正在重写以与factory
一起使用。我遇到的一个问题是延迟的ng模型,它在第一次正确更新,但在后续API调用后更新时会失去同步。
我已经做了一些挖掘,并发现这个http://learnwebtutorials.com/why-ng-model-value-should-contain-a-dot如何解决这个延迟,无济于事。为了避免无休止的if else块,我用字符串索引了我的模型:
var _brands = {
'brand1': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
'brand2': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
'brand3': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
// ~10 more
};
在默认状态下,模型更新。如果模型中已经填充了数据,问题就会开始。
说我有:
var _brands = {
'brand1': [{ID: '234', location: 'Vermont', isStarred: false, rank: '1' }, { rank: '2' }, { rank: '3' }],
'brand2': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
'brand3': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
// ~10 more
};
在更新客户端的值之后,来自API调用的数据将返回:
var _brands = {
'brand1': [{ rank: '1' }, {ID:'956', location:'Hawaii', isStarred: true, rank: '2' }, { rank: '3' }],
'brand2': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
'brand3': [{ rank: '1' }, { rank: '2' }, { rank: '3' }],
// ~10 more
};
第一个API调用正确更新模型,但任何后续请求都会延迟一个。世界上到底发生了什么?任何人都可以解释这个过程吗?
工厂:
var _saveSelection = function (data) {
api.post('Distributor/UpdateSelection', data).then(function () {
api.get('Distributor/GetSelections').then(function (brands) {
angular.copy(_initial, _brands); //This is done to 'reset' the model.
for (var i = 0; i < brands.length; i++) {
_brands[brands[i].brand][brands[i].rank - 1] = brands[i];
}
deffered1.resolve(_brands);
});
});
return deffered1.promise;
};
var _getSelections = function () {
api.get('Distributor/GetSelections').then(function (brands) {
angular.copy(_initial, _brands); //again, I want to reset the model
for (var i = 0; i < brands.length; i++) {
_brands[brands[i].brand][brands[i].rank - 1] = brands[i];
}
deffered2.resolve(_brands);
});
return deffered2.promise;
};
return {
saveSelection: function (data) {
return _saveSelection(data);
},
getSelections: function () {
return _getSelections();
}
};
答案 0 :(得分:0)
问题是我在Controller中将对象复制到自身:
brandsService.saveSelection(data).then(
function (brand) {
angular.copy(brand, $scope.brand); //Here
$scope.closeDistributorSelection();
},
function () {
//handle error
});
我不知道工厂已经在写我的$ scope了。道歉!
固定代码:
brandsService.saveSelection(data).then(
function (brand) {
$scope.closeDistributorSelection();
},
function () {
//handle error
});