How can I update a directive when a service finish

2019-09-06 09:49发布

In an AngularJS app, I have a service that uses $http and returns a promise. I have a controller which requires the service. In the controller DataService.then(function(data){ scope.viewModel.data = data;})

Then I have a directive with isolate scope. scope: { data: '='} then do something with scope.data inside the directive.

Finally the html

<div ng-controller="myCtrl">
    <div my-cool-directive="" data="viewModel.data"></div>
</div>

My question is this presents a chicken before the egg scenario. When the service data is hard coded, all is well and glorious, however when using async $http to actually call a server and get data, scope.data is null inside the directive. How can I properly get the directive the data it needs when the service call finishes and the controller scope property is set. I do not want the directive to have a dependency on the service. I prefer that the controller will drive the directive model. Is $emit or $broadcast the way to go and use a $watch? Basically eventing? or is there a preferred way to do this? I'm certain others have faced this exact issue. I would like the directive to continue to have isolate scope as I may want to extend at some point. I did try to Google first but I don't think I was phrasing the question correctly.

1条回答
不美不萌又怎样
2楼-- · 2019-09-06 10:15
<div my-cool-directive="" data="viewModel.data" ng-if="viewModel.data"></div>

should do the trick.

You could also create a watch in the directive, so that the callback function of the watch is called when the data changes from undefined to something else.

查看更多
登录 后发表回答