mindparse mindparse - 4 months ago 39
AngularJS Question

Using ng-init with async operations

Is it possible to use ng-init that make an async call whilst inside an ng-repeat?

For example consider the following:

<div ng-repeat="order in orders">
<md-list>
<md-list-item>
{{order.id}}
</md-list-item>

<md-list-item ng-init="detail = getOrderDetail(order.id)">
{{detail.itemName}}
</md-list-item>
</md-list
</div>


I'd like to call a function for each item being repeated over which will go and fetch some extra data over http.

So in my getOrderDetail I have something this kind of thing:

function getOrderDetail(id) {
return myService.getOrderDetails(id).then(function(orderDetail){
return orderDetail;
});
}


This doesnt work for me, as the
detail.itemName
in my second
md-list-item
does not resolve to anything, but I can see the network request made and if I add a breakpoint in my function call I do see the order detail returned with the
itemName
property present.

Is there a limitation when using ng-init that prevents it working\re-evaluating for async operations?

Thanks

Answer

There I can see couple of things wrong implemented

  1. Another wrong thing is you shouldn't be using ng-init for this case
  2. This is not how you can make it working, like you are considering that, data returned from promise will directly put inside a variable.

I'd make those call when I get data & will put data in order object of that element so that I can grab details later from that particular order only

angular.forEach(orders, function(order){
    getOrderDetail(id).then(function(response){
       order.detail = response;
    })
});

HTML

<div ng-repeat="order in orders">
    <md-list>
        <md-list-item>
            {{order.id}}
        </md-list-item>
        <md-list-item>
            {{order.detail.itemName}}
        </md-list-item>
    </md-list>
</div>