I'm calling a function from my custom directive on button click.
This is the code I've in my JSP
<input type="button" value="button" text="{{item.id}}" data-href="divSlide" show-notifications>
This is my custom directive
hello.directive("showNotifications", ["$interval", function($interval, $scope) {
return {
restrict: "A",
link: function(scope, elem, attrs) {
//On click
$(elem).click(function() {
console.log('before');
scope.$parent.getJSON(scope.text);
if ($('tr#' + $(this).data("href")).is(":visible")) {
$('tr#' + $(this).data("href")).remove();
} else {
console.log('after');
$(this).closest('tr').after('<tr id="' + $(this).data("href") + '"><td colspan="5">' + $('#' + $(this).data("href")).html() + '</td></tr>');
}
});
},
scope:{
text: "@text"
}
};
}]);
And this is my function
$scope.getJSON= function(id){
jsonService.getJSONData(id).then(function(data){
$scope.data= [];
$scope.data= data['dataList'];
console.log('insidejson');
}
});
};
When I execute the code the console prints the logs in the below order,
before
after
insidejson
But ideally it should be
before
insidejson
after
Why is it executing the next statement after the function call before the function gets executed?
What am I doing wrong?
$.getJSON
is async. You need to wait for it to finish. return the promise fromgetJSON
and doscope.$parent.getJSON().then(....)
. – RGraham Apr 13 '15 at 11:30