Why my $Scope. $watch doesn’t work

Asked

Viewed 309 times

1

Does anyone have any idea why mine doesn’t work $scope.$watch, that model $scope.paciente.telefones is connected to a combobox.

$scope.$watch('paciente.telefones', function(oldv, newv) {
    var existeCelularComEnvioSms = false;
    angular.forEach($scope.paciente.telefones, function(tel) {
        if (tel.envioSms == true) {
            existeCelularComEnvioSms = true;
        } else if(existeCelularComEnvioSms == true) {
            tel.envioSms = false;
        }
    });
});
  • 1

    Leonardo, why isn’t it working? Error returns, or something like that? Please add this information to the question.

  • only one observation, the parameters are reversed, the correct is: newv, oldv

2 answers

1

You need to use the $watch passing by true as the third argument:

  $scope.$watch('paciente.telefones', function(oldv, newv) {
    console.log(oldv, newv);
    var existeCelularComEnvioSms = false;
    angular.forEach($scope.paciente.telefones, function(tel) {
        if (tel.envioSms == true) {
            existeCelularComEnvioSms = true;
        } else if(existeCelularComEnvioSms == true) {
            tel.envioSms = false;
        }
    });
 }, true); //<= true (terceiro argumento)

According to the official documentation, the third argument allows value comparison instead of comparison by reference. Take a look at the link I passed and research on objectEquality.

0

Try to check the behavior change to apply the values:

$scope.$watch('paciente.telefones', function(newv, oldval) {

    if (newv !== oldval) {
        var existeCelularComEnvioSms = false;
        angular.forEach($scope.paciente.telefones, function(tel) {
            if (tel.envioSms == true) {
                existeCelularComEnvioSms = true;
            } else if(existeCelularComEnvioSms == true) {
                tel.envioSms = false;
            }
        });
    }
}, true);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.