Nithin
Nithin

Reputation: 45

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.

Upvotes: 1

Views: 129

Answers (2)

Nighthawk2730
Nighthawk2730

Reputation: 173

This is what it looks like with the 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);

            } 
        });
    };

This works without the infinite loop

Upvotes: 1

Nighthawk2730
Nighthawk2730

Reputation: 173

There maybe a way to do this by changing the way you actually update the model; however, other than possibly finding a way to register/unregister the watch in the if statement; this may not be a very good idea.

Upvotes: 1

Related Questions