Angularjs ng-show基于回调

Mal*_*k13 8 javascript angularjs

我是棱角分明的,所以也许我错过了一些东西.

在我的注册表格中,我需要用户提供一个位置.根据他们是否允许/支持navigator.geolocation,我想显示一个下拉列表来选择一个位置.

控制器.

$scope.showLoc = true;
if(navigator && navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(pos){
        $scope.showLoc = false;
    },function(err){
        $scope.showLoc = true;
    });
}
Run Code Online (Sandbox Code Playgroud)

和我的形式:

<form class="form-horizontal" name="register"  ng-controller="RegisterCtrl"  ng-submit="registerUser()"> .... 
<div ng-show="showLoc" accesskey="">
    test
</div>
....
 </form>
Run Code Online (Sandbox Code Playgroud)

这种方法对我不起作用.任何见解将不胜感激.

Mat*_*erg 14

每当你在angularjs之外进行某种形式的操作时,例如用jquery进行ajax调用,或者像你的例子一样抓住地理位置,你需要让angular知道更新自己.我看了你的jsfiddle并改变了你的一些代码,看起来像这样:

var app = angular.module('myApp', []);
app.controller('RegisterCtrl',function($scope){
     $scope.showLoc = false;   
     navigator.geolocation.getCurrentPosition(function(pos){
             $scope.showLoc = true;
             $scope.$apply();
        },function(err){           
             $scope.showLoc = false;
             $scope.$apply();            
        });
});
Run Code Online (Sandbox Code Playgroud)

现在showLoc在更新时变为true.这是使用$ apply()方法的文档http://docs.angularjs.org/api/ng.$ro​​otScope.Scope#$apply

jsFiddle http://jsfiddle.net/yLFNP/6/

编辑:我的答案已编辑,但我不同意编辑.虽然你可以在$ scope.showLoc = false周围包装$ apply方法,使其"更短"你实际上只保存1个字符(半冒号).此外,我倾向于在一堆逻辑之后喜欢$ apply方法,而不是将所有内容包装在其中.如果我在范围内做了更多的事情,你要么必须另外写一个如此:

$scope.$apply($scope.var1 = newValue1);
$scope.$apply($scope.var2 = newValue2);
$scope.$apply($scope.var2 = newValue3);
Run Code Online (Sandbox Code Playgroud)

我觉得矫枉过正,或者你可以使用函数方法:

$scope.$apply(function(){
    $scope.var1 = newValue1;
    $scope.var2 = newValue2;
    $scope.var3 = newValue3;
});
Run Code Online (Sandbox Code Playgroud)

或者直接在需要"应用"的代码之后:

$scope.var1 = newValue1;
$scope.var2 = newValue2;
$scope.var3 = newValue3;
$scope.$apply();
Run Code Online (Sandbox Code Playgroud)

通过一直使用这种方法,您的代码很容易转移并且非常易读.更少的线并不总是最好的方法.