想象一下,我有一个商店控制器中的商品列表。然后用户点击其中一个项目,它使用另一个控制器,如何获取项目控制器中的项目?
.controller('store', function($scope,$http,$state) {
$http({
method: 'GET',
url: $rootScope.hostname + '/api/products',
}).then(function successCallback(response) {
$scope.items = response.data.product;
}, function errorCallback(response) {
alert(response.data)
});
$scope.GoItem = function(data){
//data
$state.go('app.item');
}
})
.controller('item', function($scope,$http) {
//how to get the data here?
})
答案 0 :(得分:1)
编辑:我误解了这个问题。由于您试图在控制器之间传递,因此您有几个选择。
答案 1 :(得分:1)
使用$ stateParams执行此操作。
app.controller('store', function($scope, $http, $state) {
$scope.items = [{
'id': "1234",
'name': 'XYZ'
}, {
'id': "123456",
'name': 'ABC'
}]
$scope.GoItem = function(data) {
$state.go('app-item', {
'item': JSON.stringify(data)
});
}
})
app.controller('item', function($scope, $http, $stateParams) {
console.log(JSON.parse($stateParams.item))
$scope.item = JSON.parse($stateParams.item)
//how to get the data here?
})
创建了工作的Plunker。希望它能解决你的问题。 https://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2?p=preview
答案 2 :(得分:1)
您可以将参数作为$state.go('app.item', {'item':'my item'});
中的第二个参数发送。然后解析状态配置中的参数并将已解析的项目传递给控制器。
.controller('StoreCtrl', function($scope,$http,$state) {
$http({
method: 'GET',
url: $rootScope.hostname + '/api/products',
}).then(function successCallback(response) {
$scope.items = response.data.product;
}, function errorCallback(response) {
alert(response.data)
});
$scope.GoItem = function(data){
//data
$state.go('app.item', {'itemData', myItem});
}
})
.controller('ItemCtrl', function($scope, $http, itemData) {
//how to get the data here?
})
在您的州配置中:
$stateProvider
.state('store', {
url:'/store',
templateUrl: 'store.html',
controller: 'StoreCtrl'
})
.state('item', {
url:'/item',
templateUrl: 'item.html',
controller: 'ItemCtrl',
params: {
myItem: ''
},
resolve: {
name: function($stateParams) {
return $stateParams.myItem;
}
}
})
答案 3 :(得分:0)
另一个选项可能是$ state.go(' app.item',{param1:var1,param2:var2});
希望它有用并且寻找。
https://forum.ionicframework.com/t/pass-data-with-state-go/2897/2
答案 4 :(得分:0)
如果要将此数据传递到应用程序的任何位置。使用$ rootScope。$ broadcast
例如:
.controller('StoreCtrl', function($scope,$http,$state,$rootScope) {
$http({
method: 'GET',
url: $rootScope.hostname + '/api/products',
}).then(function successCallback(response) {
$scope.items = response.data.product;
}, function errorCallback(response) {
alert(response.data)
});
$scope.GoItem = function(data){
//data
$rootScope.$broadcast("passData", yourdata);
$state.go('app.item');
}
})
在你的第二个控制器上:
.controller('item', function($scope,$http) {
$scope.$on("passData", function(dataRecieved) {
console.log(dataRecieved);
});
})
您也可以使用$ stateParams。这更像是角度2方法(EventEmitter)。