Link to home
Start Free TrialLog in
Avatar of YZlat
YZlatFlag for United States of America

asked on

AngularJS service to retain global data

I am new to angular and need to keep some global data throuhout my application.  The data I need to keep is a key-value pair data. Here is the service I am trying to add to my app:

 app.service("DataService", function (MyKey, MyValue) {
        var data_item = {};
        data_item.Key =MyKey;
        data_item.Value=MyValue;
        this.MyData.push(data_item);

    });

Open in new window


Is what I am doing correct?

Also how do I access this service to add data or to retrieve data? Do I need to inject this service into each controller?
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
A note on your original code -
 app.service("DataService", function (MyKey, MyValue) {
        var data_item = {};
        data_item.Key =MyKey;
        data_item.Value=MyValue;
        this.MyData.push(data_item);

    });

Open in new window

When we setup a service we inject the dependencies we want to use in the service not the values we will be adding to it. That is done with functions as shown in the example in the previous post.
Avatar of YZlat

ASKER

@Julian Hansen, I do not want to use factory, but service
Avatar of YZlat

ASKER

also i will not be using ng-model in inputs, but variables from my controllers. I want to add items to the array from the controller code
@Julian Hansen, I do not want to use factory, but service
They are effectively the same thing, A factory just allows you to run some initialisation code before instantiating the factory object - but once instantiated they are identical in every way. To change the factory into a service just do this
    .service('DataService', function() {
      // Create a reference to ourself
      var vm = this;
    
      // Initialise the data structure
      vm.data = { };
    
      // Function to set an item in the map
      vm.setItem = function(key, value) {
        vm.data[key] = value;
      }
    
      // Function to retrieve a value from the map
      vm.getItem = function(key) {
        if (vm.data[key] != undefined) {
          return vm.data[key];
        }
        return false;
      }
    
      // Function to get all the items in the map
      vm.getAllItems = function() {
        return vm.data;
      }
    })

Open in new window

Working sample here
also i will not be using ng-model in inputs, but variables from my controllers. I want to add items to the array from the controller code
The controller is adding the data
      vm.items = DataService.getAllItems();
      ...
      DataService.setItem(key, value);

Open in new window

Where you get the key values from is irrelevant - the method of adding them to the service is the same.
Avatar of YZlat

ASKER

@Julian Hansen my data sample is actually different. It is not a conventional key-value pair but just a pair of values, I just might not have expressed myself correctly.

So I'd need to store an array of two-value items.
Could I do something like that?

 vm.setItem = function(FirstID, SecondID) {
     	data_item.FirstID=FirstID;
        data_item.SecondID=SecondID;
        vm.data.push(data_item);
      }

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of YZlat

ASKER

Thank you!

I defined the service in y base controller as follows:

(function () {
    var app = angular.module("MyApp", ["ui.router"]);

    app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);

    function BaseControllerFunc($scope, $http, $state) {
        
       ...
    }
    
    //add service
    app.service("DataService", function () {
        // Create a reference to ourself
        var vm = this;

        // Initialise the data structure
        vm.data = {};

        // Function to set an item in the map
        vm.setItem = function (FirstID, SecondID) {
            vm.data[FirstID] = SecondID;
        }

        // Function to retrieve a value from the map
        vm.getItem = function (FirstID) {
            if (vm.data[FirstID] != undefined) {
                return vm.data[FirstID];
            }
            return false;
        }

        // Function to get all the items in the map
        vm.getAllItems = function () {
            return vm.data;
        }

    });
//end add service

})();

Open in new window



Now I have a number of controllers in the following format:

angular.module("MyApp").controller("MyCtrl", ["$scope", "$state", "$http", MyCtrlFunction]);

function MyCtrlFunction($scope, $state, $http) {

  ...

}

Open in new window


How do I inject my service into my controllers?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of YZlat

ASKER

Thank you! Will test it out
Avatar of YZlat

ASKER

One last thing. I have utilized the second version you provided:

.service('DataService', function() {
  // Create a reference to ourself
  var vm = this;

  // Initialise the data structure
  vm.data = [];

  // Function to set an item in the map
  vm.setItem = function(FirstID, SecondID) {

	var new_item = {
		FirstID: FirstID,
		SecondID: SecondID
		
	}
	vm.data.push(new_item);
  }

  // Function to retrieve a value from the map
  vm.getItem = function(FirstID) {
	for(var k in vm.data) {
		if (vm.data[k].FirstID == FirstID) {
			return vm.data[k];
		}
	}
	
	return false;
  }

  // Function to get all the items in the map
  vm.getAllItems = function() {
	return vm.data;
  }
})

Open in new window


First I add data and then try to check what got added:

DataService.setItem(1, "Test");
console.log("data added is " +DataService.getItem(1).SecondID);

Open in new window


and get an error:

TypeError: Cannot read property 'SecondID' of undefined

Open in new window

Did a copy and paste of both lines to my sample - works fine

Updated controller
  // Controller function
  function mainController(DataService)
  {
    // Create a reference to ourself
    var vm = this;
	
	DataService.setItem(1, "Test");
	console.log("data added is " +DataService.getItem(1).SecondID);

	// Initialise with the DataService items
    vm.items = DataService.getAllItems();
	vm.searchItem = false;
	vm.findItem = function(item) {
		vm.searchItem = DataService.getItem(item);
	}
    // Handle the Add Item button click
    vm.addItem = function(key, value) {
      DataService.setItem(key, value);
	  
      // Clear the inputs
	  vm.FirstID = vm.SecondID = '';
    }
  }

Open in new window

Updated sample here
View result in console.
Avatar of YZlat

ASKER

Thank you for all your help!
You are welcome.