问题
I'm trying to share data between controllers but once the data is set in my service it won't change again.
The Idea
I have a page of items I'm calling coupons and clicking on an item in coupons takes you to a single-coupon. When I click an item in coupons I want to save the item data in a service so that I can have access to it in single-coupon
The Service
.service('userService', function() {
var userService = this;
userService.sharedObject = null;
})
Some Code inside CouponsCtrl
.controller('CouponsCtrl', function($scope, $state, userService) {
$scope.couponClick = function(coupon) {
userService.sharedObject = coupon;
$state.go('single-coupon');
}
})
The Issue
This works the first time like you would expect but then if I go back to coupons and click a new coupon item then the single-coupon page still shows the old data! What do I need to do differently?
回答1:
Basically your service should have getter and setter which would set & get data
Service
.service('userService', function() {
var userService = this;
userService.sharedObject = {};
userService.getCoupon = function(){
return userService.sharedObject.Coupon;
}
userService.setCoupon = function(value){
userService.sharedObject.Coupon = value;
}
});
Then you could easily set a value of data by using set setCoupon
& getData by getCoupon
method
CouponsCtrl
.controller('CouponsCtrl', function($scope, $state, userService) {
$scope.couponClick = function(coupon) {
userService.setCoupon(coupon);
$state.go('single-coupon');
}
});
SingleCouponCtrl(singleCouponCtrl will get value by)
.controller('singleCouponCtrl', function($scope, $state, userService) {
//other code here
if($state.params.id == 0) //id is of coupon id
$scope.coupon = userService.setCoupon({}); //for your issue
$scope.coupon = userService.getCoupon();
});
回答2:
If your goal is to move data between one state and another, ui-router already provides for this behavior:
$stateProvider.state('coupon', { url: '/coupon/:paramOne/:paramTwo', .... });
$state.go('app.page', { paramOne: 'testOne', paramTwo: 'testTwo });
Then, you che retrive this parameters injecting $stateParams into your Controller,
来源:https://stackoverflow.com/questions/29797940/ionic-use-service-to-share-data-between-controllers