angularjs - Angular $ watch空值错误

标签 angularjs error-handling watch angular-ngmodel

我的 Controller 中有这个:

     $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>

但是当我打开我的 View 时,我遇到了这个错误:
Error: undefined is not an object (evaluating 'newValue.formatted_address')

如何避免这种错误?是否有更好的解决方案来观看此值“Erreur ...”并开始调用confirmPopup? 谢谢。

最佳答案

您的'infos.location'不是对象,可能您尚未初始化它或将其初始化为字符串。

我想看看如何初始化infos对象或整个 Controller 。

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

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

或者,如果ion-google-place初始化infos.location,则可以仅检查infos.location(即函数内部的newValue)是否(不是undefined),而忽略(跳过)这种情况。
 $scope.$watch('infos.location', function(newValue, oldValue) {
        if (newValue && newValue.formatted_address == 'Erreur ...') {
            ...
        }
    }, true);

关于angularjs - Angular $ watch空值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38815006/

相关文章:

javascript - 使用 AngularJS 获取图像请求

error-handling - 第172和218行的Corona SDK错误,没有文件名,只有问号

javascript - 通过下拉菜单在数组之间切换需要相当多的时间。我该如何减少它? Angularjs、IvhTreeview

angularjs - 使用 expressjs 时下载的 .pdf 文件已损坏

javascript - 使用 Angular 服务并且不更改函数调用中的变量

r - SMOTE困难,矩阵上的下标数量不正确

windows-7 - Webpack --watch 在 Windows 上不起作用(也不是 webpack-dev-server)

makefile - 有没有更智能的替代 “watch make”?

javascript - $routeUpdate 未在 Angular 业力单元测试中广播?

ios - 尝试将多个图像上传到Firebase : 2 Errors in SWIFT 4, FIREBASE 5.0.0