当服务完成加载到 AngularJS 的控制器中时,如何更新指令 [英] How can I update a directive when a service finishes loading in a controller in AngularJS
问题描述
在 AngularJS 应用程序中,我有一个使用 $http
并返回承诺的服务.我有一个需要该服务的控制器.在控制器中 DataService.then(function(data){ scope.viewModel.data = data;})
然后我有一个隔离范围的指令.scope: { data: '='}
然后对指令中的 scope.data 做一些事情.
最后是 html
<div my-cool-directive="" data="viewModel.data"></div>
我的问题是这在鸡蛋场景之前呈现了一只鸡.当服务数据被硬编码时,一切都很好,但是当使用 async $http
实际调用服务器并获取数据时,指令中的 scope.data 为 null.当服务调用完成并设置控制器范围属性时,如何正确获取指令所需的数据.我不希望指令依赖于服务.我更喜欢控制器将驱动指令模型.$emit
或 $broadcast
是使用 $watch
的方法吗?基本上是活动?或者有没有更好的方法来做到这一点?我敢肯定其他人也遇到过这个确切的问题.我希望指令继续具有隔离范围,因为我可能想在某个时候扩展.我确实先尝试过谷歌,但我认为我没有正确表达这个问题.
<div my-cool-directive="" data="viewModel.data" ng-if="viewModel.data"><<;/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屋!