问题描述:

i have code like below, the code is an angular directive. The code is used to calculate the distance between two places by using coordinates, my problem is the directive result (scope.hasil = dist) doesn't appear in the view but appear in the console (console.log(dist)). What should I do so that the results can appear on view ? thanks :)

directive

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;

}

});

}

};

});

view

<distance ori="-7.048443, 110.441022" dest="-7.048264, 110.440388"></distance>

网友答案:

Use $scope.$apply to refresh the view after changing the property:

scope.$apply(function () {
    scope.hasil = dist;
});

When the link function is called, the DOM is actually populated already. So changing the scope value will not re-render the DOM by default. Use $apply will trigger another $digest cycle and update the view.

网友答案:

@joy's answer is probably the most correct. Additionally a trick my team takes advantage of to have $apply run automatically is to use $timeout like so:

$timeout(function() {
    calcRoute(ori,dest, function (err, dist) {
            if (!err) {
              scope.hasil = dist;
              console.log(dist);
            }else{
                scope.hasil = err;
            }
    });
});
相关阅读:
Top