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(); }
Alternative 3:
controller('MyController', function ($scope, myService) { $scope.forbidden = function() { return myService.getData().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?