Matteo Scandolo | 8005623 | 2017-07-10 16:24:41 -0700 | [diff] [blame] | 1 | import './field.scss'; |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 2 | import {IXosConfigHelpersService} from '../services/helpers/config.helpers'; |
| 3 | import {IXosFormHelpersService} from '../form/form-helpers'; |
| 4 | import * as _ from 'lodash'; |
| 5 | |
| 6 | class FieldCtrl { |
| 7 | static $inject = ['$attrs', '$scope', 'ConfigHelpers', 'XosFormHelpers']; |
| 8 | // $inject = ['$onInit']; |
| 9 | |
| 10 | public field: any; |
| 11 | public name: string; |
| 12 | public ngModel: any; |
| 13 | public getType = this.XosFormHelpers._getFieldFormat; |
| 14 | public formatLabel = this.ConfigHelpers.toLabel; |
| 15 | |
| 16 | constructor( |
| 17 | private $attrs: ng.IAttributes, |
| 18 | private $scope: ng.IScope, |
| 19 | private ConfigHelpers: IXosConfigHelpersService, |
| 20 | private XosFormHelpers: IXosFormHelpersService |
| 21 | ) { |
| 22 | |
| 23 | } |
| 24 | |
| 25 | public isEmptyObject = (o: any) => o ? Object.keys(o).length === 0 : true; |
| 26 | |
| 27 | $onInit() { |
| 28 | if (!this.name) { |
| 29 | throw new Error('[xosField] Please provide a field name'); |
| 30 | } |
| 31 | if (!this.field) { |
| 32 | throw new Error('[xosField] Please provide a field definition'); |
| 33 | } |
| 34 | if (!this.field.type) { |
| 35 | throw new Error('[xosField] Please provide a type in the field definition'); |
| 36 | } |
| 37 | if (!this.$attrs['ngModel']) { |
| 38 | throw new Error('[xosField] Please provide an ng-model'); |
| 39 | } |
| 40 | |
Matteo Scandolo | e7e052d | 2017-07-31 19:54:31 -0700 | [diff] [blame] | 41 | // NOTE set default value (if any) |
| 42 | if (this.field.default && !angular.isDefined(this.ngModel)) { |
| 43 | if (this.field.type === 'number') { |
| 44 | this.ngModel = parseInt(this.field.default, 10); |
| 45 | } |
| 46 | else { |
| 47 | this.ngModel = this.field.default; |
| 48 | } |
| 49 | } |
| 50 | |
Matteo Scandolo | ee655a1 | 2016-12-19 15:38:43 -0800 | [diff] [blame] | 51 | |
| 52 | if (this.field.type === 'array') { |
| 53 | this.$scope.$watch(() => this.ngModel.length, () => { |
| 54 | this.field.availableOptions = _.difference(this.field.options, this.ngModel); |
| 55 | }); |
| 56 | } |
| 57 | |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | export const xosField: angular.IComponentOptions = { |
| 62 | template: require('./field.html'), |
| 63 | controllerAs: 'vm', |
| 64 | controller: FieldCtrl, |
| 65 | bindings: { |
| 66 | ngModel: '=', |
| 67 | name: '=', |
| 68 | field: '=' |
| 69 | } |
| 70 | }; |