Javascript AngularJS:回调定义正确吗?

Javascript AngularJS:回调定义正确吗?,javascript,angularjs,callback,ionic-framework,steroids,Javascript,Angularjs,Callback,Ionic Framework,Steroids,我试图打印一个对象列表,显示它们的名称及其与用户位置之间的距离。我通过GET检索数据,并根据纬度和经度计算距离。但是,我的作用域数组的长度仍然为0。我猜我的回调架构有问题,但我似乎无法解决 控制器: angular.module('ionicApp', ['ionic']).controller('objectCtrl', function($scope, $http) { $scope.objects = []; $http.get('http://url.com/getobjects.php

我试图打印一个对象列表,显示它们的名称及其与用户位置之间的距离。我通过GET检索数据,并根据纬度和经度计算距离。但是,我的作用域数组的长度仍然为0。我猜我的回调架构有问题,但我似乎无法解决

控制器:

angular.module('ionicApp', ['ionic']).controller('objectCtrl', function($scope, $http) {
$scope.objects = [];
$http.get('http://url.com/getobjects.php').then(function (resp) {
    for (var i = 0; i < resp.data.length; i++) {
        getDistance(resp.data[i].lat, resp.data[i].lng, (function(index){
            return function(dist){
                $scope.objects[index] = {
                    name: resp.data[index].name,
                    distance: dist
                };
            }
        })(i));
    }
}, function (err) {
    console.error('ERR', err);
    alert("error");
});

知道我的代码有什么问题吗?谢谢。

看起来像是$digest循环之外出现的
getDistance
回调。因此,您应该尝试手动启动它:

$scope.objects[index] = {
    name: resp.data[index].name,
    distance: dist
};
$scope.$apply();
或使用
$timeout
服务:

getDistance(resp.data[i].lat, resp.data[i].lng, (function (index) {
    return function (dist) {
        $timeout(function() {
            $scope.objects[index] = {
                name: resp.data[index].name,
                distance: dist
            };
        });
    }
})(i));
而不是

        $scope.objects[index] = {
            name: resp.data[index].name,
            distance: dist
        };
替换

        $scope.objects.push({
            name: resp.data[index].name,
            distance: dist
        });

这两种方法中哪一种是“更好”的?我现在已经实现了第一个(非常好),因为我想我可以避免附加的函数定义。我的假设正确吗?谢谢!第二个更可靠,因为在完成前一个摘要之前,它不会尝试运行摘要。因此不会出现“$digest ready in progress”错误。请不要使用
$apply
,这很少是一个好的做法。只需使用
$q
承诺包装
navigator.geolocation.getCurrentPosition
,不需要$apply/$timeout。
        $scope.objects.push({
            name: resp.data[index].name,
            distance: dist
        });