I'm developing application using Ionic Framework and there's problem I can't solve. I have few views that are steps and must share data, user can also step back, go to some else views and come back later. His input should be stored until last step is finished then I can persist model and I need new empty one.
I used factory for this, but I can't find a way to clear object that is returned. Is it possible? What's some other approaches that I can use here?
app.js
.state('topup', {
url: "/topup",
abstract: true,
templateUrl: "templates/topup/topup.html",
controller:'TopupCtrl'
})
.state('topup-1', {
url: "/topup-1",
templateUrl: "templates/topup/topup-1.html",
controller:'TopupCtrl'
})
.state('topup-2', {
url: "/topup-2",
templateUrl: "templates/topup/topup-2.html",
controller:'TopupCtrl'
})
controllers.js
.controller('TopupCtrl', function($scope, $state, TopupData, HistoryData) {
$scope.data = TopupData.getCurrent();
$scope.selectOperator = function(operator) {
$scope.data.Operator = operator;
$state.go("topup-2");
};
$scope.acceptTopup = function(){
HistoryData.getHistory().push($scope.data);
console.log(HistoryData.getHistory());
TopupData.setCurrent({});
$state.go("main");
};
})
services.js
.factory('TopupData', function () {
var service = {};
var Model = {};
service.setCurrent = function(value)
{
Model = value;
};
service.getCurrent = function(value)
{
return Model;
};
return service;
})
Try this way.
console.log(HistoryData.getHistory());
var resetObj = {};
TopupData.setCurrent(resetObj);
$state.go("main");
I'd suggest you to don't define a controller on state level, if they are of the same name, re initializing same controller on state change is not good idea.
HTML
<div ng-controller="TopupCtrl">
<ui-view></ui-view>
</div>
CODE
.state('topup', {
url: "/topup",
abstract: true,
templateUrl: "templates/topup/topup.html"
})
.state('topup-1', {
url: "/topup-1",
templateUrl: "templates/topup/topup-1.html"
})
.state('topup-2', {
url: "/topup-2",
templateUrl: "templates/topup/topup-2.html"
})
Then i don't think so you will need factory anymore, as there no need to share a scope.
Changing code like this, solved my problem:
var resetObj = {};
TopupData.setCurrent(resetObj);
$state.go("main").then(function(){
$ionicHistory.clearHistory();
$ionicHistory.clearCache();
});