Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果地理位置不可用,则禁用按钮_Javascript_Angularjs - Fatal编程技术网

Javascript 如果地理位置不可用,则禁用按钮

Javascript 如果地理位置不可用,则禁用按钮,javascript,angularjs,Javascript,Angularjs,所以我有一个主页,其中有3个按钮-登录,注册和恢复帐户。我想禁用所有这些按钮,并在地理位置不可用或用户不允许浏览器共享其位置时显示消息 $scope.btnDisabled = false; $scope.errorMsg = null; $scope.checkBrowser = function () { if (navigator.geolocation.getCurrentPosition) { // let's find out where you are!

所以我有一个主页,其中有3个按钮-登录,注册和恢复帐户。我想禁用所有这些按钮,并在地理位置不可用或用户不允许浏览器共享其位置时显示消息

$scope.btnDisabled = false;
$scope.errorMsg = null;

$scope.checkBrowser = function () {
    if (navigator.geolocation.getCurrentPosition) {
        // let's find out where you are!
        console.log("Got your location");
        $scope.btnDisabled = false;       
    } else {
        $scope.errorMsg = "Warning. Could not locate your position. Please enable your GPS device.";
        //disable the buttons
        $scope.btnDisabled = true;
        //Show errorMessage
        return true
    }

    //errorMessage visibility is set false
    return false;
}
到目前为止,我还没有成功地禁用按钮或显示错误消息,除了警告消息

这是我得到警告信息的方式:

function getPosition() {
    console.group("geoloc getPosition");
    if (window.navigator) {
        console.log("api supported");
        navigator.geolocation.getCurrentPosition(success, error);
    } else {
        console.log("api fallback");
    }
    console.groupEnd();
}

function success(pos) {
    console.log("geoloc pos ", pos);
}

function error(err) {
    alert("Geolocation identification failed.");
    $scope.btnDisabled = true;
}
为什么$scope.btnDisable不能在错误函数中工作?

您应该使用

navigator.geolocation.getCurrentPosition(
   function() {
      $scope.btnDisabled=false;
      $scope.$apply();
   }, function() {
      $scope.btnDisabled=true;
      $scope.$apply();
   }
});
知道getCurrentPosition将调用回调而不是返回某些内容是非常重要的!看

您还必须调用$scope。$apply,因为您将在处理非角度回调时禁用任何角度更新

在第二个示例中执行此操作,按钮状态应得到更新

另请参见$scope.$apply