I have set up two controllers (Controller A and Controller B) and a service (Service). I am attempting to sync the data from controller A to the service, and present that information to Controller B.
我已经设置了两个控制器(控制器A和控制器B)和一个服务(服务)。我试图将控制器A中的数据同步到服务,并将该信息提供给控制器B.
Within my Service, I've established a variable confirmdata
and get and set functions:
在我的服务中,我已经建立了一个变量confirmdata并获取和设置函数:
function setData(data) {
confirmdata = angular.copy(data);
}
function getData() {
return confirmdata;
}
In controller A I've created a function sync
to sync information from the controller to the service:
在控制器A中,我创建了一个从控制器到服务的函数syncto同步信息:
this.sync = function () {
var data = {
payment: this.getpayment()
}
Service.setData(data);
In controller B I've assigned a function as:
在控制器B中,我分配了一个功能:
this.sync = function () {
this.viewData = Service.getData();
console.log('TestingData', this.viewData);
For a reason I am unaware of; my console log simply returns undefined when it should be returning the results of the getpayment()
function. Am I missing something here?
我不知道的原因;我的控制台日志只返回undefined,它应该返回getpayment()函数的结果。我在这里错过了什么吗?
1 个解决方案
#1
0
The fact that you are getting undefined would indicate that you haven't initialized 'confirmdata' in your service. Whether this is the actual issue though, isn't clear. For a simple example, I would design your service like this:
您未定义的事实表明您尚未在服务中初始化'confirmdata'。这是否是实际问题,目前尚不清楚。举个简单的例子,我会像这样设计你的服务:
myApp.factory('sharedService', [function () {
var confirmdata = {};
return {
setData: function (newData) { confirmdata = newData; },
getData: function getData() { return confirmdata; }
}
}]);
Take a look at this plunker. It gives an example of data being shared between controllers via a service.
看看这个plunker。它给出了通过服务在控制器之间共享数据的示例。
#1
0
The fact that you are getting undefined would indicate that you haven't initialized 'confirmdata' in your service. Whether this is the actual issue though, isn't clear. For a simple example, I would design your service like this:
您未定义的事实表明您尚未在服务中初始化'confirmdata'。这是否是实际问题,目前尚不清楚。举个简单的例子,我会像这样设计你的服务:
myApp.factory('sharedService', [function () {
var confirmdata = {};
return {
setData: function (newData) { confirmdata = newData; },
getData: function getData() { return confirmdata; }
}
}]);
Take a look at this plunker. It gives an example of data being shared between controllers via a service.
看看这个plunker。它给出了通过服务在控制器之间共享数据的示例。