首页 > 解决方案 > How to bystep this $watch infinite loop?

问题描述

In my angularJs file, I have a watch set on a variable that is set by my md-select

<md-select ng-model="NC.common.commonType" ng-model-options="{trackBy: '$value.id'}" flex="25" placeholder="Common Type" ng-disabled="!NC.isEdit()">

In my controller:

scope.$watch('NC.common.commonType', function (new, old) {
        modal.launchModal('Common type changed', '<p>Are you sure?</p>')
        .then((result) => {
            if (!result) {
                vm.module.placementType = angular.copy(oldValue);
        });
    }, true);

So when they select another option; it triggers a modal. This modal asks you if you are sure you want to change the modal. If you say no, I set the watched variable back to the old value; and ignore the new value. This triggers the $watch infinite loop.

标签: angularjs

解决方案


这就是 ng-change 的样子

<md-select ng-model="NC.common.commonType" ng-value="NC.common.commonType" ng-change="CC.onChange(NC.common.commonType,'{{NC.common.commonType}}')">

        vm.onChange = function(newValue, oldValue) {
        modal.launchModal('Placement type changed', '<p>Are you sure?</p>')
        .then((result) => {
            if (!result) {
                vm.module.placementType = angular.copy(oldValue);

            } 
        });
    };

这在没有无限循环的情况下有效


推荐阅读