AngularJS两款相互影响的手表

时间:2016-06-01 08:39:00

标签: angularjs

我的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 - >这会产生无限循环。

我现在的问题是,如果我可以通过停止类似的传播来阻止这种情况吗?

1 个答案:

答案 0 :(得分:0)

您可以使用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(); 停止/启动观看流程,如下所示:

Spring MVC

编辑:查看官方文档“返回此侦听器的注销功能”。 https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope

相关问题