Angularjs ng-show based callback

I am new to angular, so maybe I am missing something.

In my registration form, I need a place from the user. Based on whether they allow / support .geolocation navigation, I want to show a drop down menu to select a location.

controller.

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

and my form:

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

This approach does not work for me. Any insight would be appreciated.

+8
javascript angularjs
source share
1 answer

Whenever you perform any operation outside of angularjs, for example, making an ajax call with jquery or capturing geolocation, as your example, you need to tell angular to update itself. I looked at your jsfiddle and changed part of your code to look like this:

 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(); }); }); 

And now showLoc will change true to update. It uses the documentation on using the $ apply () method http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply

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

Edit: my answer has been edited, but I do not agree with the editing . Although you can wrap the $ apply method around $ scope.showLoc = false to make it shorter. You really only save 1 character (half density). Also, I like the $ apply method after a bunch of logic instead of wrapping everything in it. If there were more things that I did in the field, you would need to write each additional, for example:

 $scope.$apply($scope.var1 = newValue1); $scope.$apply($scope.var2 = newValue2); $scope.$apply($scope.var2 = newValue3); 

What I find redundant, or you can use the function method:

 $scope.$apply(function(){ $scope.var1 = newValue1; $scope.var2 = newValue2; $scope.var3 = newValue3; }); 

Or immediately after the code that requires "application":

 $scope.var1 = newValue1; $scope.var2 = newValue2; $scope.var3 = newValue3; $scope.$apply(); 

By executing this method all the time, you code is easily portable and very readable. Also, fewer lines are not always the best method.

+14
source share

All Articles