在视图之间共享数据

share data between views

我正在使用 Ionic Framework 开发应用程序,但遇到无法解决的问题。 我有几个步骤的视图,必须共享数据,用户也可以退后一步,转到其他视图,稍后再回来。他的输入应该存储到最后一步完成,然后我可以保留模型并且我需要新的空模型。

我为此使用了工厂,但找不到清除返回对象的方法。可能吗? 我可以在这里使用哪些其他方法?

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;
})

试试这个方法。

console.log(HistoryData.getHistory());
var resetObj = {};
TopupData.setCurrent(resetObj);
$state.go("main");

像这样更改代码,解决了我的问题:

    var resetObj = {};
    TopupData.setCurrent(resetObj);
    $state.go("main").then(function(){
        $ionicHistory.clearHistory();
        $ionicHistory.clearCache();
    });

我建议您不要在状态级别定义控制器,如果它们同名,则在状态更改时重新初始化相同的控制器不是个好主意。

HTML

<div ng-controller="TopupCtrl">
    <ui-view></ui-view>
</div>

代码

.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"
})

那么我认为您将不再需要工厂,因为不需要共享范围。