【发布时间】:2017-08-12 09:57:52
【问题描述】:
您好,我有一个非常大(并且还在不断增长)的 AngularJS 表单,其中包含几页输入。在后端,只有一个保存到数据库的 post 端点。我目前正在使用$cookies 在本地保存先前步骤中的数据,以防用户想要返回并编辑某些内容。这样做是危险的还是坏主意?到目前为止它似乎工作得很好,但我担心我正在做一些我不知道的愚蠢的事情。
我正在使用components 和angular-ui-router 来路由这样的视图:
namespace NewClientForm {
angular
.module('app', ['ui.bootstrap', 'ngCookies', 'ui.router', 'google.places', 'cwill747.phonenumber'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/clientInfo');
$stateProvider
.state('clientInfo', {
url: '/clientInfo',
template: '<h3>Client Info</h1></br><clientinfo></clientinfo>'
})
.state('billing', {
url: '/billing',
template: '<h3>Billing</h1></br><billing></billing>'
})
.state('licensing', {
url: '/licensing',
template: '<h3>Licensing</h1></br><licensing></licensing>'
})
.state('users', {
url: '/users',
template: '<h3>Add Users</h1></br><users></users>'
})
.state('quoting', {
url: '/quoting',
template: '<h3>Quoting Preferences</h1></br><quoting></quoting>'
});
})
.component('billing', {
templateUrl: 'app/form/templates/billing.html',
bindings: {},
controller: 'FormController'
})
.component('clientinfo', {
templateUrl: 'app/form/templates/clientInfo.html',
bindings: {},
controller: 'FormController'
})
.component('licensing', {
templateUrl: 'app/form/templates/licensing.html',
bindings: {},
controller: 'FormController'
})
.component('users', {
templateUrl: 'app/form/templates/users.html',
bindings: {},
controller: 'FormController'
})
.component('spinner', {
templateUrl: 'app/form/templates/spinner.html',
bindings: {},
controller: 'FormController'
})
.component('quoting', {
templateUrl: 'app/form/templates/quoting.html',
bindings: {},
controller: 'FormController'
});};
然后我在$cookies 上使用putObject 方法来保存这样的数据:
控制器:
save = (name: string, obj: any, configObj: any, state: string) => {
this.$cookies.putObject(name, obj, configObj);
this.$log.debug(this.$cookies.getAll());
this.$state.go(state);
};
查看:
<button class="btn btn-primary" ng-if="!clientInfoForm.$invalid"
style="float:right;"
ng-click="$ctrl.save('clientInfo', $ctrl.clientInfo, {expires:$ctrl.expireDate}, 'billing')">
Next
</button>
最后,我在我的函数中使用$cookies.getObject 从$cookie 填充我的ng-model(s):
populateFromCookie = () => {
this.clientInfoCookie = this.$cookies.getObject('clientInfo');
if (this.clientInfoCookie) {
if (this.clientInfoCookie.hasOwnProperty('FirstName')) {
this.clientInfo.FirstName = this.clientInfoCookie.FirstName;
};
if (this.clientInfoCookie.hasOwnProperty('LastName')) {
this.clientInfo.LastName = this.clientInfoCookie.LastName;
};
if (this.clientInfoCookie.hasOwnProperty('title')) {
this.clientInfo.title = this.clientInfoCookie.title;
};
};
};
任何关于我如何改进它的建设性批评或建议将不胜感激。谢谢!
【问题讨论】:
标签: angularjs cookies angular-ui-router angularjs-components