Need Help with services or global variables

Hi everyone,
I am brand new to ionic and pretty new to coding and so I thought I would ask you guys for some help.

I am trying to create an empty global variable (var choice={}). Then when the user clicks an item on a certain page in a list, the code assigns a specific text to the global variable such as ion-item href=“book1.html” ng-click="choice=“book1"” (not sure if this is even correct). Then this newly set global variable choice (which should be a string=book1) will be used to identify a certain object in an array in the controller such as or listofarrays.choice.price and so forth. The global variable needs to be assigned, passed, and then referenced by all of the different controllers. Please if anyone can tell me how this can be done or if there is another way to go about it. I would love to use a service for the variable and the arrays, but I don’t know how to add one into ionic framework. Thanks in advance

Don’t use service for Global variable. You have many options to share data using

  • $rootScope
  • using factory
  • Factory Update
  • Function factory and $watch function
  • Sessionstorage and localstorage

See these two article -…

i am not agree with you…
if you can avoid putting stuff on the rootscope --> use services/factories… what you prefer

and your “Factory-Update” is wrapping everything in getter and setter methods instead of manipulating the value directly (but this is something with code styling and coding guildelines)
if you want more of that read this:

And please avoid using useless usages of $watch.
If you understood the way references work in javascript… you can simply store your values (directly or with getter and setters) and every usage of the reference will automatically update their value if the base value changes…

If you need the value persistent (through app starts or reloads) --> store it in localstorage and if you need this value for ever (localstorage gets cleared in some cases --> write it to the filesystem in the dataDirectory)

You right localstorage and sessionstorage much better .Thanks

Thanks for the response :slight_smile: I looked over the article and I saw that it used (input text) to assign the text to the variable. Is there a way I could make clicking a button assign a specific text to the variable and then use it pull data from an object in an array. I can’t find anywhere that shows how this can be done.

great…is there a way I could set the value of the variable using an ng-click…so everytime the user clicks button 1 variable value changes to button1 and then I use that as a reference to find specific object in an array called things. so i would then in my view I could just use things.(variable).name or things.(variable).price and so on… Thanks for the help :slight_smile: