我有一个如下所示的代码,用于计算两点之间的距离,这是我的 ionic 项目的代码。我使用了 allenhwkim 的 Angularjs-google-maps,我想将代码转换为 Angular 范围函数,以便它可以在我的 View 上运行。顺便说一下,我从这个论坛的最后一个问题中得到了这个代码。
计算距离:
var calcRoute = function(origin,destination,cb) {
var dist;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb(null, response.routes[0].legs[0].distance.value / 1000);
}
else {
cb('pass error information');
}
});
};
下面的代码用于运行该函数并将结果保存在 $scope.A 中,以便我可以通过在我的 View 上键入 {{A}} 来调用结果
calcRoute("-7.048443, 110.441022","-7.048264, 110.440388", function (err, dist) {
if (!err) {
$scope.A = dist;
}
});
问题是,我只能使用我的 Controller 中的函数并使用 $scope 发送结果,但是如何将代码例如转换为 {{ calc(ori,dest ) }} 并返回我的 View 中的距离。
我尝试这样做:
$scope.calc = function(ori,dest){
var calcRoute = function(origin,destination,cb) {
var dist;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
cb(null, response.routes[0].legs[0].distance.value / 1000);
}
else {
cb('pass error information');
}
});
};
calcRoute(ori,dest, function (err, dist) {
if (!err) {
return dist;
}else{
console.log("failed");
}
});
return calcRoute();
};
并在我的View中调用该函数,如下所示:
{{calc("-7.048443, 110.441022","-7.048264, 110.440388")}}
它不起作用, 返回未定义并在下面显示控制台错误:
Error: [$interpolate:interr] Can't interpolate:
{{calc("-7.048443, 110.441022","-7.048264, 110.440388")}}
InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object
希望有人能帮助我,谢谢:))
最佳答案
不确定您是否可以即时计算函数并打印返回值。
你能做的是:
- 将您的函数绑定(bind)到范围函数
$scope.calc = function(x,y){...}
- 在里面进行通常的赋值
$scope.A = dist
。 - 在 View 中只需打印
{{A}}
。 - 要调用该函数,只需使用
calc(ori,dest)
。 (从你的代码中我没有得到你应该调用它的地方)。
关于javascript - 如何将函数变成 Angular 范围函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008042/