我是ng的新手。在这里,我有一个场景,我需要将从成功收到的响应带到另一个控制器。我尝试过以下代码,但我无法达到目标。
代码:
$scope.received = function(){
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
//The data received here I need t take to mydataController
$location.path('/success');
})
when('/success', {
templateUrl: 'ngtemplates/success/success.html',
controller: 'mydataController'
}).
app.controller('mydataController',
[ '$scope', '$http',function($scope, $http,$location) {
//I want the success data here in some function
}]);
请帮帮我
答案 0 :(得分:0)
您可以将服务用于您的目的。
服务
myApp.factory('dataService', function() {
var _data;
this.setData = function(someData) {
_data = someData; // better use angular.copy() function
}
return {
data : _data;
}
});
HTTP CALL:
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
//The data received here I need t take to mydataController
// before using dataService, make sure you inject it to the controller
dataService.setData(data);
$location.path('/success');
});
<强> CONTROLLER 强>
app.controller('mydataController',
[ '$scope', '$http',function($scope, $http,$location, dataService) {
//I want the success data here in some function
var someData = dataService.data;
}]);
答案 1 :(得分:0)
你有2个解决方案。您可以提供服务或使用活动。
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
$rootScope.$broadcast('dataReceived', data);
$location.path('/success');
});
在mydataController中:
$rootScope.$on('dataReceived', function(e, data) {
// do something with the data
}
或者您可以提供服务以在两者之间共享数据。
angular.module('demo').service('myDataService', function() {
this.data = null;
this.setData = function(data) {
this.data = data;
}
});
在控制器中:
$http({
url : "/generic/getdata",
method : 'GET',
}).success(function(data) {
myDataService.setData(data);
$location.path('/success');
});
在mydataController中:
$scope.something = myDataService.data;