Best (idiomatic) way to update data from a service in AngularJS

I encountered a "problem" with AngularJS, services and features.

This is actually not a problem (I found several ways to make it work), but I would like to know if I am doing the right thing, or if what I do can lead to problems in the future

I have a service that contains some global data; a service has two methods: get data () RefreshData ()

refreshData starts some work (calling rest, etc.) and is called at points in different controllers in response to user actions (pressing buttons, etc.).

getData (obviously) is called to return data.

In controllers, how should I use it to access data and put it in scope so that it can be accessed from view (s)?

Alternative 1:

controller('MyController', function ($scope, myService) { $scope.data = myService.getData(); //use data in functions and in the view, ex: ng-hide="data.forbidden" 

Alternative 2:

 controller('MyController', function ($scope, myService) { $scope.data = function() { return myService.getData(); } //use data() in functions and in the view, ex: ng-hide="data().forbidden" 

Alternative 3:

 controller('MyController', function ($scope, myService) { $scope.forbidden = function() { return myService.getData().forbidden; } //... one function for each data.member used in this view //usage in the view: ng-hide="forbidden()" 

Alternative 4: use $ apply or $ watch

I am currently using the second approach, as it works even when a new controller is not created (think of different particles on the same page with different controllers).

Is there any reason? Or is there a better approach?

+4
source share
1 answer

It depends on the use. Alternative 1 or 3 can be used when you want to fill in data when the page loads or when the controller is initialized. Alternative 2 can be used when you want to activate a data update by clicking a button or other actions. Alternative 4 can be used when you want data loading to be dependent on data changes in another data model. Therefore, I think that every alternative that you posted makes sense in the right scenario.

+4
source

Source: https://habr.com/ru/post/1493674/


All Articles