问题是我似乎无法将信息从 Controller 1 发送到 Controller 2...我有设置/获取数据的服务,但它不起作用。我收到的实际错误是 Controller 1 的 dataService.getData 不是一个函数...当它在其他地方工作时。
服务 1(在其自己的文件中)
app.service('dataService', function() {
var data, queried;
return {
setData: function(queryData) {
this.data = queryData;
this.queried = false;
},
getData: function() {
this.queried = true;
return this.data;
}
};
});
Controller 1(发送信息)
app.controller('MyCtrl', ['$scope', '$location', '$state', function($scope, $location, $state, dataService) {
anotherService.functionName(function(err, data) {
// do some things here
actualService.doesntWork(function(err, data) {
if (!err) {
var query = {};
query.someField = data.someField;
dataService.setData(query);
$state.go("go.somewhere.else");
}
});
});
}]);
Controller 2(获取信息)
app.controller('MyCtrl2', ['$scope', '$location', '$state', function($scope, $location, $state, dataService) {
$scope.buttonPressed = function() {
console.log(dataService.getData());
}
}]);
最佳答案
您没有在 MyCtrl
和 MyCtrl2
中注入(inject)服务 dataService
,请确保在使用它之前注入(inject)依赖项。
Controller
app.controller('MyCtrl', ['$scope', '$location', '$state','dataService', //<-added dependency here
function($scope, $location, $state, dataService) {
anotherService.functionName(function(err, data) {
// do some things here
actualService.doesntWork(function(err, data) {
if (!err) {
var query = {};
query.someField = data.someField;
dataService.setData(query);
$state.go("go.somewhere.else");
}
});
});
}]);
Controller 2
app.controller('MyCtrl2', ['$scope', '$location', '$state','dataService',//<-added dependency here
function($scope, $location, $state, dataService) {
$scope.buttonPressed = function() {
console.log(dataService.getData());
}
}]);
关于angularjs - 似乎无法将数据从一个 Controller 传递到另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804855/