我正在尝试使用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')) ;
}

答案 0 :(得分:1)
应该是这样的。
您的代码存在问题
1)首先你在controller
中犯了错误。没有用]);
2)您将string
而非variable
(SD_date
和ED_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;