AngularJS:回调定义得当吗?

时间:2014-10-17 11:48:59

标签: 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').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");
});

getDistance的:

function getDistance(lat2, lon2, callback) {
    navigator.geolocation.getCurrentPosition(function onSuccess(position) {
        var lat1 = position.coords.latitude;
        var lon1 = position.coords.longitude;
        var radlat1 = Math.PI * lat1 / 180;
        var radlat2 = Math.PI * lat2 / 180;
        var radlon1 = Math.PI * lon1 / 180;
        var radlon2 = Math.PI * lon2 / 180;
        var theta = lon1 - lon2;
        var radtheta = Math.PI * theta / 180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist);
        dist = dist * 180 / Math.PI;
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344;
        callback(dist);
    }, function onError(error) {
        alert("no location found:"+ error);
    });
}

任何想法我的代码有什么问题?感谢。

2 个答案:

答案 0 :(得分:1)

看起来{$ 1}}回调出现在$ digest周期之外。所以你应该尝试手动启动它:

getDistance

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

$timeout

答案 1 :(得分:0)

而不是

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

替换

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