如何更新指令,当一个服务完成在AngularJS控制器装 [英] How can I update a directive when a service finishes loading in a controller in AngularJS
问题描述
在一个AngularJS应用程序,我有一个使用 $ HTTP
,并返回一个承诺的服务。我有需要服务的控制器。在控制器 DataService.then(功能(数据){scope.viewModel.data =数据;})
然后我有分离范围指令。范围:{数据:'='}
然后做一些与该指令内scope.data P>
最后,HTML
< DIV NG控制器=myCtrl>
< DIV我爽-指令=数据=viewModel.data>< / DIV>
< / DIV>
我的问题是presents鸡蛋方案之前,一只鸡。当业务数据是很难codeD,一切都很好,光荣的,但使用异步 $ HTTP
当实际调用服务器并获取数据,scope.data为空该指令中。我怎样才能得到正确的指令,当服务呼叫完成和控制器范围属性设置它所需要的数据。我不想指令对服务的依赖。我preFER控制器将驱动指令模式。为 $发出
或 $广播
去和使用方式的 $观看
?基本上事件触发?或者是有一个preferred方式做到这一点?我敢肯定其他人都面临着这个确切的问题。我想指令继续有隔离范围,因为我可能要在某些时候延长。我曾尝试谷歌第一,但我不认为我是正确的措辞问题。
< DIV我爽-指令=数据=viewModel.dataNG-IF =视图模型。数据>< / DIV>
应该做的伎俩。
您也可以在指令中制造出一款腕表,让腕表的回调函数被调用时,从不确定到别的数据的变化。
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.
<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.
这篇关于如何更新指令,当一个服务完成在AngularJS控制器装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!