Angularjs 在广播或加载视图时有角度?

Angularjs 在广播或加载视图时有角度?,angularjs,Angularjs,我有一个简单的服务,可以获取设备的gps位置并进行广播: 还有一个默认位置 service('currentPosition', function($rootScope){ //default current position var myLocation = {lat: 59.3325800, long: 18.0649000} $rootScope.$broadcast('location', myLocation) if (

我有一个简单的服务,可以获取设备的gps位置并进行广播:

还有一个默认位置

service('currentPosition', function($rootScope){
        //default current position
        var myLocation = {lat: 59.3325800, long: 18.0649000}
        $rootScope.$broadcast('location', myLocation)

        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(function(position) {
                myLocation.lat = position.coords.latitude;
                myLocation.long = position.coords.longitude;
                $rootScope.$broadcast('location', myLocation)
            });
        }
        return{
            getMyLocation: function(){
                return myLocation;
            }
        }
    }).
在我的应用程序的几个视图中,我想为位置的更改添加一个侦听器。我还希望在加载视图时获取值。我一直在写这样的东西:

$scope.myLocation = currentPosition.getMyLocation();
$scope.$on('location', function(scope,myLocation){
    $scope.myLocation = myLocation;
});

在我的几个控制器和指令中。有更好的方法吗?例如,通过捕获以前广播的。

当您将对
myLocation
对象的引用从您的服务传递到控制器中的
$scope.myLocation
时,它们正在使用同一对象,您不需要使用$broadcast(或任何其他通知系统)来获取更新

演示

服务将首先记录更新后的
myLocation
对象,然后经过一小段延迟后,控制器将记录其
myLocation
对象

您会注意到这两个日志都记录了更新的对象

这种情况下的问题是ui没有更新。这是因为来自navigator.geolocation.getCurrentPosition的回调发生在“Angular的世界之外”,这意味着$digest循环不会被触发,更改也不会反映在DOM中

从:

$apply()用于从外部以角度执行表达式 角度框架。(例如,从浏览器DOM事件, setTimeout、XHR或第三方库)。因为我们正在召唤 我们需要的角度框架执行适当的生命周期范围 异常处理,执行监视

就你而言:

if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(function(position) {

    $rootScope.$apply(function() {
      myLocation.lat = position.coords.latitude;
      myLocation.long = position.coords.longitude;
    });
  });
}
演示