我有如下代码,该代码是有角度的指令。该代码用于通过使用坐标来计算两个位置之间的距离,我的问题是指令结果(scope.hasil = dist
)没有出现在视图中,而是出现在控制台(console.log(dist)
)中。我应该怎么做才能使结果显示在视图上?谢谢 :)
指示
dir.directive('distance', function () {
var calcRoute = function(ori,dest,cb) {
var dist;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var request = {
origin:ori,
destination:dest,
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("error");
}
});
};
return{
restrict:"E",
scope: true,
template:"{{hasil}} km",
link: function(scope, elm, attrs) {
var ori = attrs.ori;
var dest = attrs.dest;
calcRoute(ori,dest, function (err, dist) {
if (!err) {
scope.hasil = dist;
console.log(dist);
}else{
scope.hasil = err;
}
});
}
};
});
视图
<distance ori="-7.048443, 110.441022" dest="-7.048264, 110.440388"></distance>
最佳答案
更改属性后,使用$scope.$apply
刷新视图:
scope.$apply(function () {
scope.hasil = dist;
});
调用
link
函数时,实际上已经填充了DOM。因此,默认情况下,更改scope
值不会重新呈现DOM。使用$apply
将触发另一个$digest
循环并更新视图。关于javascript - angular指令未出现在 View 中,但出现在控制台中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31839642/