将值设置为来自对象的变量后,无法获取值

时间:2017-05-22 05:02:12

标签: javascript angularjs angular-services

我正在尝试使用object.setData()[失败]获取我正在设置的变量值 - 这个setData()和getData()进入我正在导入到我正在使用的多个控制器的服务中它

控制台输出值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



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'))  ;
        
}




1 个答案:

答案 0 :(得分:1)

应该是这样的。

您的代码存在问题

1)首先你在controller中犯了错误。没有用]);

关闭它

2)您将string而非variableSD_dateED_date)传递到工厂制定者。

此外,我将其清除为key而不$rootScope'startDateCal'代替'$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>
&#13;
&#13;
&#13;