Is it bad practice for an angular directive to request data

怎甘沉沦 提交于 2019-12-10 17:53:44

问题


Consider for example a currentUser directive.

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.

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

Thanks


回答1:


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.




回答2:


There are two scenarios and it really depends on the purpose of your directive:

  1. the directive is only used to display user-data (in a complex way)
  2. the directive displays data and manipulates it (according to user-input)

SCENARIO 1

Since the only purpose of the directive it to render the data somehow, the directive should not be responsible for retrieving the data.

So you decouple the logic how to access the data and how to display the data. This way you can also use the directive for users other than the currently logged in user.

If there should be some special things visible, if the user is logged in, the directive should use ng-if or ng-show for that (and maybe a parameter to disable that view-part).

SCENARIO 2

In this case the purpose of the directive is to provide a gui for some business-logic (service functionality). Therefore the service should be injected into the directive.


Remark:

PERFORMACE

If you get the data via method-call from your service, this method will only be called once in every digest-cycle if you load the data and inject it into the directive-controller. Otherwise it may be called once for each occurance of the directive.

INTEGRITY

Remember, that if your service-method requests data via http and you are using the directive for example 3 times in a view and the directive calls the service-method itself, this will result in 3 identical requests which may have non-identical results (i.e. someone other changes the data while the requests are processed).




回答3:


It is always better to use service to reside business logic.You should use service to get data and inject that service to directive.Do not use controller to communicate between directive.Service is meant for that purpose, initiate once.



来源:https://stackoverflow.com/questions/33210331/is-it-bad-practice-for-an-angular-directive-to-request-data

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