gpt4 book ai didi

javascript - 在我的情况下如何将数据传递到不同的 Controller ?

转载 作者:行者123 更新时间:2023-12-02 17:20:15 27 4
gpt4 key购买 nike

我正在尝试为 Restful 服务创建工厂。

我需要调用服务电话。第一个调用的数据将用于获取第二个调用的数据。我的问题是我不知道如何将数据从一个 Controller 传输到另一个 Controller 。

有更好的方法来编写我的代码吗?

这是我的代码...

var app = angular.module('myApp', []);

//getting init data via service
app.factory('myService', function($http) {
var myService = {
async: function() {
var promise = $http.get('test/test.json').then(function (response) {

return response.data;
});
return promise;
}
};
return myService;
});


//retrieve data
app.controller('testCtrl', function(myService, $scope, $http) {
myService.async().then(function(data) {
$scope.data = data
//using retrieve data to get another piece of data
vay first = data[0].employee[0];
})

$http({
url: "test?" + first +'.json',
method: "GET",
}).success(function(secondData) {
$scope.secondData=secondData //How do I pass data to my secondCtrl?
})
})


app.controller('secondCtrl', function($scope) {
// I need to be able to get the secondData from testCtrl.
console.log($scope.secondData)
})

感谢您的帮助!

最佳答案

为什么不将数据作为对象存储在服务本身中,那么两个 Controller 都依赖于该服务并可以访问数据。像这样:

app.factory('myService', function($http) {
var that = this;
var myService = function($http) {
this.set = function(url) {
var promise = $http.get(url).then(function (response) {
that.data = promise.data;


});
return promise;
}
};
return new myService($http);
});

然后你的 Controller 设置并获取数据

app.controller('testCtrl', function(myService, $scope, $http) {
myService.set('someurl').then(function() {
$scope.data = myservice.data;
//using retrieve data to get another piece of data
vay first = data[0].employee[0];

myservice.set('someOtherUrl?data='+first);
})



app.controller('secondCtrl', function($scope, myservice) {
//the data object on the myservice function has been changed on the first controller and we can reasonably expect the data we need. If these 2 controllers coexist in the same space and time we can wrap this in a $watch service
console.log(myservice.data)
});

$watch服务示例

app.controller('secondCtrl', function($scope, $watch, myservice) {
$watch('myservice.data', function(newval, oldval) {
console.log(newval);
}, true)
//I will only log the newvalue of myservice.data when the data has changed. the last true argument is a neccesity so that angular will compare the values within the object
});

关于javascript - 在我的情况下如何将数据传递到不同的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24026827/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com