Share data between controllers in AngularJS snippet

One of the biggest issue I see today with people starting to code in Angular is that they don't understand how AngularJS services work very well. This was something that was hard for me to understand as well. Don't worry with time, you'll start to understand the frame a lot better and eventually you'll get cozy with services and factories.

This is not a blog post on how AngularJS services work, but a solution to solve your problems when STARTING an applications. The reason I capitalize starting is because eventually you will want to write specific services related to your application and some using something so agnostic like what I'm about to show you.

angular.module("myModuleApp").factory("DataService", function() {  
    var storage = [];

    return {
        set: function(name, value) {
            storage[name] = value;
        },
        get: function(name) {
            return storage[name];
        }
    }
});

Replace "myModuleApp" with the name of your AngularJS application. Here is how to use this between two AngularJS controllers:

angular.module("myModuleApp").controller("controller1", function($scope, DataService) {  
     $scope.sharedValue = function() {
           DataService.get("mySharedValue");
     };
     $scope.setSharedValue = function() {
           DataService.set("mySharedValue", "Controller1 Value");
     };
});
angular.module("myModuleApp").controller("controller2", function($scope, DataService) {  
     $scope.sharedValue = function() {
           DataService.get("mySharedValue");
     };
     $scope.setSharedValue = function() {
           DataService.set("mySharedValue", "Controller2 Value");
     };
});

Try it out and let me know how it works for you.