Why my $ scope. $ watch does not work

1

Does anyone have any idea why my $scope.$watch does not work, this $scope.paciente.telefones is attached 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;
        }
    });
});
    
asked by anonymous 16.04.2015 / 14:03

2 answers

1

You need to use $watch passing 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 official documentation , the third argument allows < in> comparison by value instead of comparison by reference . Take a look at the link I went through and search for objectEquality .

    
17.04.2015 / 15:22
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);
    
29.03.2018 / 14:58