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