我正在制作一个基于 MEAN 的网站。现在我正试图将数据从一个 Controller 传递到下一个 Controller ,但我似乎没有完成。选择一个选项后,我想将该值带到下一页
这是带有选择框的页面:
<div class="plumber-by-city col-sm-12 home-text-col" ng-controller="DataCtrl">
<div class="title-1">Search by cityname</div>
<select ng-model="selectedItem" ng-change="change()" ng-options="item as item.city for item in items"></select><span class="fa fa-caret-down"></span>
</div>
在更改时我想使用 DataCtrl2 将 selectedItem 传递到下一页
这是我的 DataCtrl:
app.controller('DataCtrl', function($scope,$http,getData,$location,$routeParams){
getData.getCity($scope);
$scope.change = function() {
$location.path('/plumber-in/' + $scope.selectedItem.city);
};
});
以及从数据库中检索数据的服务:
app.factory('getData', function($http){
return {
getCity: function($scope){
return $http.get("/getdata").then(function(response){
$scope.items = response.data;
$scope.selectedItem = response.data[0];
});
}
};
});
现在我不知道在第二个页面的DataCtrl2中放什么以及如何在这个页面中使用DataCtrl中的数据
最佳答案
您需要的是服务中的 Setter 和 Getter 方法。像这样
app.controller('DataCtrl',
function($scope,$http,getData,$location,$routeParams){
getData.getCity().then(function(response) {
$scope.items = response.data;
$scope.selectedItem = response.data[0];
});
$scope.change = function() {
// sets the data to the service
getData.setItem($scope.selectedItem);
$location.path('/plumber-in/' + $scope.selectedItem.city);
};
});
app.factory('getData', function($http){
return {
getCity: function(){
return $http.get("/getdata");
},
setItem: function(item) {
this.item = item;
},
getItem: function() {
return this.item;
}
};
});
app.controller('DataCtrl2',
function($scope, $http, getData,$location,$routeParams){
// get the data from the service
getData.getItem();
});
关于javascript - 在另一个 Controller 中使用来自一个 Controller 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44584429/