angular $watch空值错误

angular $watch empty value error

我的控制器里有这个:

     $scope.$watch('infos.location', function(newValue, oldValue) {
        if (newValue.formatted_address == 'Erreur ...') {
            var confirmPopup = $ionicPopup.confirm({
                title: 'Geolocalisation',
                template: 'Voulez-vous activer la géolocalisation ?'
            });
            confirmPopup.then(function(res) {
                if (res) {
                    $cordovaPreferences.show().success(function(value) {
                        //alert("Success: " + value);
                    }).error(function(error) {
                        // alert("Error: " + error);
                    })
                } else {
                    console.log('You are not sure');
                }
            });
        }
    }, true);

它监视这个输入:

<label  class="item item-input">*
   <ion-google-place placeholder="Veuillez saisir l'adresse du bien"  ng-model="infos.location"  current-location="true"/>
</label>

但是当我打开视图时出现此错误:

Error: undefined is not an object (evaluating 'newValue.formatted_address')

如何避免这种错误? Watch this value 'Erreur ...' 并开始调用 confirmPopup 是否有更好的解决方案? 谢谢。

你的 'infos.location' 不是对象,可能你还没有初始化它或将它初始化为字符串。

我想看看你是如何初始化你的 infos 对象或整个控制器的。

您可能可以通过初始化 infos 来解决此问题。

infos: {
  location: {},
  ...
}

或者,如果 ion-google-place 初始化 infos.location,你可以只检查 infos.location(即 newValue inside function)是(不是)undefined,忽略(跳过)那种情况。

 $scope.$watch('infos.location', function(newValue, oldValue) {
        if (newValue && newValue.formatted_address == 'Erreur ...') {
            ...
        }
    }, true);

我是这样想的:

$scope.infos = {
      nom: '',
      tel: '',
      location: {},
      lat: '',
      lng: ''
  };

然后在我的控制器中:

     $scope.$watch('infos.location', function(newValue, oldValue) {
        if (newValue.formatted_address == 'Erreur ...') {
            var confirmPopup = $ionicPopup.confirm({
                title: 'Geolocalisation',
                template: 'Voulez-vous activer la géolocalisation ?'
            });
            confirmPopup.then(function(res) {
                if (res) {
                    $cordovaPreferences.show().success(function(value) {
                        //alert("Success: " + value);
                    }).error(function(error) {
                        // alert("Error: " + error);
                    })
                } else {
                    console.log('You are not sure');
                }
            });
        }
    }, true);

infos.location 在我进入我的视图时没有初始化。现在可以了。谢谢大家!