Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 1 | // TODO clean this mess |
| 2 | |
| 3 | import * as _ from 'lodash'; |
| 4 | import {IXosFormHelpersService} from './form-helpers'; |
| 5 | import {IXosConfigHelpersService} from '../services/helpers/config.helpers'; |
| 6 | |
| 7 | class FormCtrl { |
| 8 | $inject = ['$onInit', '$scope', 'XosFormHelpers', 'ConfigHelpers']; |
| 9 | |
| 10 | public ngModel: any; |
| 11 | public excludedField: string[]; |
| 12 | public formField: any; |
| 13 | private config: any; |
| 14 | |
| 15 | constructor ( |
| 16 | private $scope: ng.IScope, |
| 17 | private XosFormHelpers: IXosFormHelpersService, |
| 18 | private ConfigHelpers: IXosConfigHelpersService |
| 19 | ) { |
| 20 | |
| 21 | } |
| 22 | |
| 23 | $onInit() { |
| 24 | if (!this.config) { |
| 25 | throw new Error('[xosForm] Please provide a configuration via the "config" attribute'); |
| 26 | } |
| 27 | |
| 28 | if (!this.config.actions) { |
| 29 | throw new Error('[xosForm] Please provide an action list in the configuration'); |
| 30 | } |
| 31 | |
| 32 | if (!this.config.feedback) { |
| 33 | this.config.feedback = { |
| 34 | show: false, |
| 35 | message: 'Form submitted successfully !!!', |
| 36 | type: 'success' |
| 37 | }; |
| 38 | } |
| 39 | |
| 40 | // TODO Define this list in a service (eg: ConfigHelper) |
| 41 | this.excludedField = this.ConfigHelpers.excluded_fields; |
| 42 | if (this.config && this.config.exclude) { |
| 43 | this.excludedField = this.excludedField.concat(this.config.exclude); |
| 44 | } |
| 45 | |
| 46 | this.formField = []; |
| 47 | |
| 48 | this.$scope.$watch(() => this.config, () => { |
| 49 | if (!this.ngModel) { |
| 50 | return; |
| 51 | } |
| 52 | let diff = _.difference(Object.keys(this.ngModel), this.excludedField); |
| 53 | let modelField = this.XosFormHelpers.parseModelField(diff); |
| 54 | this.formField = this.XosFormHelpers.buildFormStructure(modelField, this.config.fields, this.ngModel, this.config.order); |
| 55 | }, true); |
| 56 | |
| 57 | this.$scope.$watch(() => this.ngModel, (model) => { |
| 58 | console.log(this.ngModel); |
| 59 | // empty from old stuff |
| 60 | this.formField = {}; |
| 61 | if (!model) { |
| 62 | return; |
| 63 | } |
| 64 | let diff = _.difference(Object.keys(model), this.excludedField); |
| 65 | let modelField = this.XosFormHelpers.parseModelField(diff); |
| 66 | this.formField = this.XosFormHelpers.buildFormStructure(modelField, this.config.fields, model, this.config.order); |
| 67 | console.log(this.formField); |
| 68 | }); |
| 69 | |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | export const xosForm: angular.IComponentOptions = { |
| 74 | template: require('./form.html'), |
| 75 | controllerAs: 'vm', |
| 76 | controller: FormCtrl, |
| 77 | bindings: { |
| 78 | ngModel: '=', |
| 79 | config: '=' |
| 80 | } |
| 81 | }; |