角度指令请求数据是不好的做法吗 [英] Is it bad practice for an angular directive to request data
问题描述
以 currentUser 指令为例.
Consider for example a currentUser directive.
我可以让控制器使用服务来获取有关当前用户的数据,将其提供给指令并让指令呈现一些hello {user.name}"模板.
I could let the controller use a service to get the data about the current user, provider it to the directive and let the directive render some "hello {user.name}" template.
或者,我可以让指令依赖于某些 currentUserService,并在指令的控制器中请求 currentUserService.getCurrentUser.
Alternatively I could have the directive have a dependency on some currentUserService and in the directive's controller ask for currentUserService.getCurrentUser.
出于某种原因,两者中的一个是否明显优于另一个?我倾向于使用第一个选项,但不确定使用第二个选项是否不会因为减少所有当前用户逻辑的传播而受益...
Is one of the two significantly better then the other for any reason? I tend to go with the first option but not sure if the using the second one would not have a benefit of having all the current-user-logic less spread around...
谢谢
推荐答案
只要您从服务请求数据,我相信在指令中对其有依赖关系就可以了.
控制器的主要方面是可以访问 $scope,仅此而已.
As long as you're requesting the data from a service, I believe having a dependency toward it in a directive is fine.
The main aspect of the controller is having access to $scope, not much more.
这篇关于角度指令请求数据是不好的做法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!