2

I use $scope.data.xxxx etc in many places in my AngularJS application. Right now I am declaring $scope.data in each controller like this:

$scope.data = {}

Is there a better place for me to do this. For example could I better do this when setting up my app.js file in the .config or .run ?

Alan2
  • 23,493
  • 79
  • 256
  • 450

3 Answers3

5

Numerous places you can put it

var app= angular.module('myApp',[])

As service

app.factory('myData',function(){
  return { foo:'bar'}

});

As Value

app.value( 'myData', { foo:'bar'});

As constant

app.constant( 'myData', { foo:'bar'});

In each case would inject myData in controller, directive, another service etc to access it

app.controller('SomeController',function($scope, myData){
   $scope.data=myData;
})
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • I assumed the global `myData` could be updated in a page and get persistent to other pages. But somehow it didn't work. Can you please show us in your example how an update is performed? Thanks. – Blaise Jul 07 '14 at 18:25
  • @Blaise should be fairly easy by creating a getter and setter in a factory or service – charlietfl Jul 07 '14 at 22:33
3

You can use at least 2 options:

  • Use $rootScope as storage.

  • Use service. Services are singletons that you can inject to any controller and expose their values in a controller's scope.

I suggest you to use service (at least for me, its better way). from $rootScope all controllers can see your globals,

Good example how to use Service as storage you can see in Fiddle

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
1

Not really. if your application has a root controller that the others are nested inside you could set $scope.data there, but that probably doesn't do what you want - all of your controllers would use the same data object. If one controller changed it, it would change in every other controller as well.

Because (I presume) you want a separate $scope.data in each controller, you should continue to initialise each one separately.

joews
  • 29,767
  • 10
  • 79
  • 91
  • Actually I don't need a separate $scope.data in each controller. How about in the .run or .config could I do it there ? – Alan2 Nov 09 '13 at 19:07
  • In that case there are three options - use a parent controller (attached to, say, body), use $rootScope or define a custom service. See this answer for more detail - http://stackoverflow.com/questions/11938380/global-variables-in-angularjs?rq=1 – joews Nov 09 '13 at 19:09