Create a Service
angular.module('XYZ').service("XyzService", ["", function() {
this.data = undefined;
this.getData() {
return this.data;
}
this.setData(dataObject) {
this.data = dataObject;
}
}]);
// Or, you can create a factory as well.
angular.module('XYZ').factory('XyzFactory', ["", function () {
const obj = {};
obj.data = undefined;
obj.getData = function () {
return obj.data;
};
obj.setData = function (dataObject) {
obj.data = dataObject;
};
return obj;
}]);
//For View: HTML-1, Controller: View1Controller
angular.module('XYZ').controller("View1Controller", ["$scope", "XyzService", "XyzFactory", function($scope, XyzService, XyzFactory) {
// Here you can set data in the XyzService. e.g.
$scope.dataObject = {
"firstName" : "John",
"lastName" : "Parker"
};
// Using service.
XyzService.setData($scope.dataObject);
// Using factory
XyzFactory.setData($scope.dataObject);
}]);
For View: HTML-2, Controller: View2Controller
angular.module('XYZ').controller("View2Controller", ["$scope", "XyzService", "XyzFactory", function($scope, XyzService, XyzFactory) {
// Here, you can access data Using service.
console.log("ACCESS DATA : " + XyzService.getData());
// {"firstName" : "John", "lastName" : "Parker"}
// Here, you can access data Using factory.
console.log("ACCESS DATA : " + XyzFactory.getData());
// {"firstName" : "John", "lastName" : "Parker"}
}]);