0

I wonder what is the most elegant way to initialize/the objects that I fill from the AJAX call and are used 'concurrently' somewhere in a directive.

I have a controller with such snippet:

$scope.var1 = {};
$scope.var2 = {};
$http({
  url: "/httpService",
  method: "GET",
  params: {}
}).success(function(data, status) {
  $scope.var1 = data.some; // (*1)
  $scope.var2 = data.other;
})

I am also using a directive which binds directly to var1:

var1 : '='

and inside the directive there is some check on var1.

if (var1.prop) // (*2) {
   doSth();
}

Depending on which of (*1), (*2) gets called first, the outcome is different.

What is your advice for this case? In case I would only have one variable set at (*1) I would just use the promise got as a result of $http.

I wonder what's the most idiomatic way to do it in Angular. Combining var1 and var2 into one object seems not elegant to me.

wsk
  • 65
  • 2
  • 7
  • I don't understand why you think you need two promises. There's only one asynchronous action occuring. – Kevin B Jan 16 '15 at 17:24
  • I only pass var1 to the directive. i don't want to pass there the promise object that I get from $http. I guess that the directive should not know how I got var1, it would just be great for it to wait until var1 is filled. – wsk Jan 16 '15 at 17:35

2 Answers2

0

Make a function in your directive that gets the promise from the $http call. Give the function a callback that will do:

if (var1.prop) // (*2) {
  doSth();
}

By making that part of the callback you ensure that it wont be done until after the data has returned from the call.

You don't have two promises from one call. You have one promise and one call. Treat it as such.

Patrick Motard
  • 2,650
  • 2
  • 14
  • 23
0

If I got you right - you want to pass part of the data received asynchronously to the directive, but you don't want the directive to 'know' about data structures received.

Then you could move data request out of the controller and use services (docs, examples) as an additional layer that will handle data request and provide methods to extract var1 (or var2) directly for usage inside controller (and further in directive).

shershen
  • 9,875
  • 11
  • 39
  • 60
  • you got me right, thank you. it seems to be the most reasonable thing to do. I was also thinking about replacing `var1 = {}` with `var1 = someUnresolvedPromise` but your way is more elegant. – wsk Jan 19 '15 at 15:53