You can inject the service while defining the directive and then set up a $watch on the data. So in your case:
.directive('tree', function ($compile, myService) {
return {
// ...
link: function (scope, element, attrs) {
scope.$watch(function () {
return myService.getData();
},
function (newVal) {
if (typeof newVal !== 'undefined') {
// ...
}
}
});
}
}
});
This will watch the data for change and run the code each time the data changes.
However, if the data does not change after being set once, a better way (more efficient) would be to return a promise from the service ($http methods returns a promise directly or you can create one using the $q service) and then add your computation as a continuation to the data.
.directive('tree', function ($compile, myService) {
return {
// ...
link: function (scope, element, attrs) {
myService.getData().then(function (data) {
// ...
}, function (err) {
// Handle error
});
}
}
});