How can I update a directive when a service finishes loading in a controller in AngularJS

北城以北 提交于 2019-12-13 05:17:28

问题


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:


<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.



来源:https://stackoverflow.com/questions/25314891/how-can-i-update-a-directive-when-a-service-finishes-loading-in-a-controller-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!