我的 AngularJS 1.3 应用程序中有以下手表:
$scope.$watch('vm.reportInstitution', function(newValue, oldValue) {
if(oldValue != newValue) {
userService.getAllUsersOfInstitutionByInstitutionId(vm.reportInstitution.id).then(function successCallback(response) {
vm.optionsUser = response.data;
vm.reportUser = vm.optionsUser.length > 0 ? vm.optionsUser[0] : null;
}, function errorCallback(response) {
console.log('error in recordReport.controller.js#watch#reportInstitution');
});
}
});
$scope.$watch('vm.reportUser', function(newValue, oldValue) {
if(oldValue != newValue) {
userService.getInstitutionsOfUser(vm.reportUser.id).then(function successCallback(response) {
vm.optionsInstitution = response.data;
vm.reportInstitution = vm.optionsInstitution.length > 0 ? vm.optionsInstitution[0] : null;
}, function errorCallback(response) {
console.log('error in recordReport.controller.js#watch#reportUser');
});
}
});
因此,相互影响,例如,如果 vm.reportInstitution 更改比 vm.reportUser 设置,如果 vm.reportUser 更改,则 vm.reportInstitution 被设置 ->这会产生无限循环。
我现在的问题是,我是否可以通过停止类似的传播来防止这种情况?
如下stopwatchreportInstitution()/startwatchreportInstitution()
停止/启动监视进程:
var stopwatchreportInstitution = null ;
var stopwatchreportUser = null ;
function startwatchreportInstitution(){
stopwatchreportInstitution = $scope.$watch('vm.reportInstitution', function(newValue, oldValue) {
if(oldValue != newValue) {
userService.getAllUsersOfInstitutionByInstitutionId(vm.reportInstitution.id).then(function successCallback(response) {
vm.optionsUser = response.data;
// STOP the other watch
if (stopwatchreportUser != null) {
stopwatchreportUser();// arrete le watcher
stopwatchreportUser = null;
}
vm.reportUser = vm.optionsUser.length > 0 ? vm.optionsUser[0] : null;
}, function errorCallback(response) {
console.log('error in recordReport.controller.js#watch#reportInstitution');
});
}
});
}
startwatchreportInstitution() ;
function startwatchreportUser(){
stopwatchreportUser = $scope.$watch('vm.reportUser', function(newValue, oldValue) {
if(oldValue != newValue) {
userService.getInstitutionsOfUser(vm.reportUser.id).then(function successCallback(response) {
vm.optionsInstitution = response.data;
// STOP the other watch
if (stopwatchreportInstitution != null) {
stopwatchreportInstitution();// arrete le watcher
stopwatchreportInstitution = null;
}
vm.reportInstitution = vm.optionsInstitution.length > 0 ? vm.optionsInstitution[0] : null;
}, function errorCallback(response) {
console.log('error in recordReport.controller.js#watch#reportUser');
});
}
});
}
startwatchreportUser();
编辑:在官方文档中查看"返回此侦听器的取消注册函数"。 https://docs.angularjs.org/api/ng/type/$rootScope.Scope