我的应用程序中有多个步骤表单,我想在进行下一步之前保存它......我做了一个简单的例子,但我不确定它是否是正确的方法。我使用解析配置和服务来访问 formData。
配置
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url : '/',
controller : 'appCtrl',
templateUrl : 'partials/home.html',
resolve : {
saveform : function($state, FormData){
}
},
})
.state('home.state1', {
url: "state1",
templateUrl : 'partials/item1.html',
resolve : {
saveform : function($state, FormData){
return FormData.save();
}
},
})
.state('home.state2', {
url: "state2",
templateUrl : 'partials/item2.html',
resolve : {
saveform : function($state, FormData){
return FormData.save();
}
}
})
});
控制器
app.controller('appCtrl', function($scope, $rootScope, $state, saveform, FormData){
$scope.formData = {};
$scope.tempData = {};
$rootScope.$on('$stateChangeStart', function(event){
console.log($scope.tempData , $scope.formData)
if(!_.isEqual($scope.tempData , $scope.formData)){
console.log('OK CHANGE DETECTED, SAVE')
var temp = {}
FormData.set(angular.copy($scope.formData));
}else{
console.log('NO CHANGE')
}
});
$rootScope.$on('$stateChangeSuccess', function(event){
var temp = FormData.get();
if(Object.keys(temp).length!=0){
FormData.cancel();
angular.copy(temp, $scope.tempData );
angular.copy(temp, $scope.formData );
}
});
})
服务
app.service('FormData', function($q, $timeout){
this.formdata = {};
this.save = function(){
if(Object.keys(this.formdata).length===0)
return false;
var deferred = $q.defer();
$timeout(function() {
this.formdata.test = "YEAH TEST";
deferred.resolve(this.formdata);
//this.formdata = {};
}.bind(this), 1000);
return deferred.promise;
}
this.cancel = function(){
this.formdata = {};
}
this.set = function(data){
this.formdata = data;
}
this.get = function(){
return this.formdata;
}
})
codepen 示例:http ://codepen.io/anon/pen/RWpZGj