nightfury
nightfury

Reputation: 412

can not get values after setting values into a variable from object

I am trying to fetch values of variable that I am setting using object.setData() [ which is failing] - this setData() and getData() is into a service that I am importing into multiple controllers that I am using it.

the console out valuesoutput // ie - o/p // SD_date value> SD_date // ED_date value> ED_date // // which I want to it to be like below, what should be changed ?! // SD_date value> 455754 // ED_date value> 12345

appOne.factory('dates',function($rootScope,$timeout){
          var headInfo = [];
      return {
          setData: function (key, data) {
              headInfo[key] = data;
          },
          getData: function (key) {
              return headInfo[key];
          }      
        }
 });
 appOne.controller("ControllerOne",['$scope','$http','apiUrl','$state','$timeout','$interval','dates', function($rootScope, $http,apiUrl,$state,

$timeout,$interval,dates){
    	$scope = this;

        var SD_date = 455754;
        var ED_date = 12345;


        dates.setData('$rootScope.startDateCal ','SD_date');
        dates.setData('$rootScope.endDateCal','ED_date');
        
	

	// the below two console would generate - variable names as output 
	// ie - o/p
	//  	 SD_date value> SD_date
	//       ED_date value> ED_date
	//
	// which I want to it to be like below, what should be changed ?!
	//  	 SD_date value> 455754
	//       ED_date value> 12345
	
	        
        console.log(" SD_date value>"+dates.getData('$rootScope.startDateCal')); 
        console.log(" ED_date value>"+dates.getData('$rootScope.endDateCal'))  ;
        
}

Upvotes: 0

Views: 54

Answers (1)

Hadi
Hadi

Reputation: 17289

It should be like this.

You have some problem in your code

1) Firstly you have mistake in controller. Not closing it with ]);

2) You pass string instead of variable (SD_date and ED_date ) into factory setter.

Also i thinke its clear to pass key without $rootScope. 'startDateCal' instead of '$rootScope.startDateCal'

var appOne = angular.module("app", []);

appOne.factory('dates', function() {
  var headInfo = [];
  return {
    setData: function(key, data) {
      headInfo[key] = data;
    },
    getData: function(key) {
      return headInfo[key];
    }
  }
});
appOne.controller("ControllerOne", ['$scope', '$timeout', '$interval', 'dates', function($rootScope, $timeout, $interval, dates) {

  var SD_date = 455754;
  var ED_date = 12345;
  dates.setData('startDateCal', SD_date);
  dates.setData('endDateCal', ED_date);
  
  console.log(" SD_date value>" + dates.getData('startDateCal'));
  console.log(" ED_date value>" + dates.getData('endDateCal'));

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ControllerOne">

</div>

Upvotes: 1

Related Questions