我对数据对象有一个监视:
$scope.$watch('data', function(after, before) {
$scope.saveData();
}, true);
我还有一个弹出的模态来编辑上面的一些数据对象的属性。但是,如果我通过此模式编辑任何属性,但决定“取消”,它仍会保存已编辑的属性。
当模态弹出时,有没有办法禁用该手表?
答案 0 :(得分:4)
$ watch返回一个函数。如果你打电话给你,你会删除你的观察者
angular docs,向下滚动至$ watch并查看返回值
var myWatcher = $scope.$watch('data', function(after, before) {
$scope.saveData();
}, true);
myWatcher(); // removes your watcher
修改强>: 使用angular-ui-bootstrap,您可以将注销功能传递给模态控制器。来自docs的修改示例:
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return {
data: data
myWatcher: myWatcher // you can call items.myWatcher() in your modal controller
};
}
}
});
但我不知道重新启用观察者的简单方法(函数调用或类似方法)。你将不得不重新设置它。
modalInstance.result.then(function (data) {
$scope.data = data;
}, function () {
// callback for cancel, here you could re-apply the watcher
});