blob: f05a8e4dfd874d41685e459dd412cf5ff50d1a04 [file] [log] [blame]
Matteo Scandolo80056232017-07-10 16:24:41 -07001import './field.scss';
Matteo Scandoloee655a12016-12-19 15:38:43 -08002import {IXosConfigHelpersService} from '../services/helpers/config.helpers';
3import {IXosFormHelpersService} from '../form/form-helpers';
4import * as _ from 'lodash';
5
6class 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 Scandoloe7e052d2017-07-31 19:54:31 -070041 // 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 Scandoloee655a12016-12-19 15:38:43 -080051
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
61export 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};