1
votes

For Angular 1, I have an AJAX call that is made in the controller (as it is dependent on another set of data that is returned during the route resolve) and once the response is back, the data is passed down to directives. Since the data doesn't come back until after the directives are compiled, the directives initially gets an undefined for that data passed from the controller and would only get the data if I am watching that scope value inside each of the directive. Is there a better way where I don't have to use $scope.$watch or any event listeners, such as $broadcast/$on? I don't want to exhaust the digest cycle with too much watchers.

Here's a mock structure:

<parent>
  <directive1 data="manipulateDataReturnedFromAJAXCall"></directive1>
</parent>

//template for directive1
<div>
  <directive2 ng-if="data" attr1="data.field1"></directive2>
<div>
1
Use the directive only when the data is there, using ng-if.JB Nizet
@JBNizet - That's a good suggestion. What if I have a directive that lives inside directive1 and I want directive1 to render first with the pre-existing data and to only show a feature if valid data is returned back from the later AJAX call?PBandJen
Then you'll need a watch. Or use a component's $onChanges, but I guess they use a watch internally.JB Nizet

1 Answers

-1
votes

What about using a callback in your http service.

//Controller
MyHTTPService.getData(function(data){
    $scope.manipulateDataReturnedFromAJAXCall = data;
})

//MyHTTPService service
return{
    getData : function(fct){
       $http.get("url/to/data").then(function(response){
           fct(response.data);
       })
    }
}