我有如下代码,代码是一个角度指令。代码用于通过坐标计算两个地方之间的距离,我的问题是指令结果(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>
答案 0 :(得分:2)
更改属性后使用$scope.$apply
刷新视图:
super.onCreate(savedInstanceState)
调用scope.$apply(function () {
scope.hasil = dist;
});
函数时,实际上已经填充了DOM。因此,默认情况下,更改link
值不会重新呈现DOM。使用scope
会触发另一个$apply
周期并更新视图。
答案 1 :(得分:1)
@ joy的回答可能是最正确的。另外,我的团队利用自动$ apply运行的技巧是使用$ timeout,如下所示:
$timeout(function() {
calcRoute(ori,dest, function (err, dist) {
if (!err) {
scope.hasil = dist;
console.log(dist);
}else{
scope.hasil = err;
}
});
});