YZlat
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:
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?
app.service("DataService", function (MyKey, MyValue) {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
@Julian Hansen, I do not want to use factory, but service
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 serviceThey 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;
}
})
Working sample herealso 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 codeThe controller is adding the data
vm.items = DataService.getAllItems();
...
DataService.setItem(key, value);
Where you get the key values from is irrelevant - the method of adding them to the service is the same.
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?
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);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!
I defined the service in y base controller as follows:
Now I have a number of controllers in the following format:
How do I inject my service into my controllers?
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
})();
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) {
...
}
How do I inject my service into my controllers?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you! Will test it out
ASKER
One last thing. I have utilized the second version you provided:
First I add data and then try to check what got added:
and get an error:
.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;
}
})
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);
and get an error:
TypeError: Cannot read property 'SecondID' of undefined
Did a copy and paste of both lines to my sample - works fine
Updated controller
View result in console.
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 = '';
}
}
Updated sample hereView result in console.
ASKER
Thank you for all your help!
You are welcome.
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.