这个场景很简单:
- 用户打开模式窗口。
- 用户输入事件名称(本例中的事件是与域相关的事件,例如“ session ”或“比赛”)。
- 事件在 ok 时保存(
ok()
->“保存”剩余调用到后端)。 - 成功创建事件后,系统会再次调用后端来检索更新的事件列表。
问题:我不明白如何严格同步流程,其中保存事件后模式窗口关闭,模式窗口关闭后事件列表更新。
更新:经过更多测试,我注意到竞争条件,有时出现新事件,有时不出现。
在反复尝试返回 Angular 大约 2 年之后,我再次陷入 promise 。
我现在所拥有的是在调用ok()
之后,事件被保存并且模式窗口被关闭,但仪表板的事件列表没有更新。当我再次创建新事件时,结果是我在仪表板上看到了包含先前创建的事件的更新列表,但不是我刚刚创建的事件...
app.controller('ModalDemoCtrl', function ($scope, $uibModal, $log, eventService) {
console.log("ModalDemoCtrl Controller Loaded.");
$scope.items = ['item1', 'item2', 'item3'];
$scope.animationsEnabled = true;
$scope.open = function (size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'eventModal.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
eventService.getEvents().success(function (data) {
$log.info("Received number of events:" + data.length);
$scope.$parent.events = data;
}).error(function (status) {
$log.info("Error with status: " + status);
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
app.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items, eventService, $log) {
console.log("ModalInstanceCtrl Controller Loaded.");
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function (event) {
eventService.saveEvent(event).success(function (data) {
console.log("savedEvent")
}).error(function (status) {
});
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
最佳答案
以下是避免竞争条件的方法...
在模态 Controller (ModalInstanceCtrl
) 中,您想要做的是通过服务保存事件,然后然后关闭模态,解析结果
与您的新事件
$scope.ok = function (event) {
eventService.saveEvent(event).success(function (data) {
console.log("savedEvent");
$uibModalInstance.close($scope.selected.item);
}).error(function (status) {
// you might want to dismiss the modal here, it's up to you
});
};
此外,您可以直接在 eventModal.html
模板中使用 $uibModalInstance
方法来减少 Controller 代码
<button type="button" ng-click="$dismiss('cancel')">Cancel</button>
关于angularjs - Angularjs Bootstrap 模式窗口,在ok()上保存事件并更新父范围的事件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123042/