AngularJS在foreach中的范围对象中更新值

时间:2017-03-10 16:07:12

标签: angularjs scope

我需要在表单提交中重新计算范围对象中的一些值。

所以我得到了:

 $scope.submit = function() {
       if ($scope.searchPlace) {
       var address = $scope.searchPlace + ', ' $scope.land;
       geocodeAddress(address, function(latLng){
          angular.forEach($scope.places,function(value,key){
            var distance = getDistance(value.latitude,value.longitude,latLng.lat(),latLng.lng())
            value.distance = distance;
           });
         });
     }
 };

$ scope.places类似于[{' name':' place_a',' distance':0},{' name&#39 ;:' place_b','距离':0}]

但我看不到前端范围对象的任何变化。我错过了什么?

以上是上面使用的两个功能

var getDistance = function(lat1,lon1,lat2,lon2) {
            var R = 6371; // Radius of the earth in km
            var dLat = deg2rad(lat2-lat1);  // deg2rad below
            var dLon = deg2rad(lon2-lon1);
            var a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            var d = R * c; // Distance in km
            return d;
        }


var geocodeAddress = function(address, callback) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    callback(results[0].geometry.location);
                } else {
                    console.log("Geocode was not successful for the following reason: " + status);
                }
            });
        };

1 个答案:

答案 0 :(得分:0)

如果getDistance函数返回一个promise,你应该像这样使用它:

getDistance(value.latitude,value.longitude,latLng.lat(),latLng.lng()).then(function(response){
    var distance = response.data;
    value.distance = distance;
});