I am facing a "problem" with AngularJS, services and scope.
It is not really a problem (I found a couple of ways to make it work), but I would like to know if I am doing the right thing, or if what I am doing can lead to problems in the future
I have a service that holds some global data; the service has two methods: getData() refreshData()
refreshData triggers some work (rest invocation etc.) and it is called at precise points inside different controllers, in response to user actions (button clicks etc).
getData is (obviously) called to get the data back.
In the controllers, how should I use it to access the data and put it in scope, so that it can be accessed from the 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 about different partials in the same page, with different controllers).
Does it make any sense? Or is there a better approach?
It depends on the usage. The Alternative 1 or 3 maybe used when you want to populate the data when the page is loaded or when the controller is initialized. The Alternative 2 can be used when you want to trigger the data refresh by clicking on a button or some other actions. Alternative 4 can be used when you want data load is driven by data change on other data model. So I think every alternative you posted makes sense in the correct scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With