问题
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.
回答1:
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).
回答2:
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.
来源:https://stackoverflow.com/questions/27989363/angularjs-two-promises-from-one-http-call