blob: ab5f1d25a8928556a97ca79c19416766150f1b13 [file] [log] [blame]
Matteo Scandolofb46ae62017-08-08 09:10:50 -07001
2/*
3 * Copyright 2017-present Open Networking Foundation
4
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8
9 * http://www.apache.org/licenses/LICENSE-2.0
10
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18
Matteo Scandolo80056232017-07-10 16:24:41 -070019import './field.scss';
Matteo Scandoloee655a12016-12-19 15:38:43 -080020import {IXosConfigHelpersService} from '../services/helpers/config.helpers';
21import {IXosFormHelpersService} from '../form/form-helpers';
22import * as _ from 'lodash';
23
24class FieldCtrl {
25 static $inject = ['$attrs', '$scope', 'ConfigHelpers', 'XosFormHelpers'];
26 // $inject = ['$onInit'];
27
28 public field: any;
29 public name: string;
30 public ngModel: any;
31 public getType = this.XosFormHelpers._getFieldFormat;
32 public formatLabel = this.ConfigHelpers.toLabel;
33
34 constructor(
35 private $attrs: ng.IAttributes,
36 private $scope: ng.IScope,
37 private ConfigHelpers: IXosConfigHelpersService,
38 private XosFormHelpers: IXosFormHelpersService
39 ) {
40
41 }
42
43 public isEmptyObject = (o: any) => o ? Object.keys(o).length === 0 : true;
44
45 $onInit() {
46 if (!this.name) {
47 throw new Error('[xosField] Please provide a field name');
48 }
49 if (!this.field) {
50 throw new Error('[xosField] Please provide a field definition');
51 }
52 if (!this.field.type) {
53 throw new Error('[xosField] Please provide a type in the field definition');
54 }
55 if (!this.$attrs['ngModel']) {
56 throw new Error('[xosField] Please provide an ng-model');
57 }
58
Matteo Scandoloe7e052d2017-07-31 19:54:31 -070059 // NOTE set default value (if any)
Matteo Scandolof1e68cd2017-09-05 17:30:34 -070060 if (angular.isDefined(this.field.default) && angular.isUndefined(this.ngModel)) {
Matteo Scandoloe7e052d2017-07-31 19:54:31 -070061 if (this.field.type === 'number') {
62 this.ngModel = parseInt(this.field.default, 10);
63 }
64 else {
65 this.ngModel = this.field.default;
66 }
67 }
68
Matteo Scandoloee655a12016-12-19 15:38:43 -080069
70 if (this.field.type === 'array') {
71 this.$scope.$watch(() => this.ngModel.length, () => {
72 this.field.availableOptions = _.difference(this.field.options, this.ngModel);
73 });
74 }
75
76 }
77}
78
79export const xosField: angular.IComponentOptions = {
80 template: require('./field.html'),
81 controllerAs: 'vm',
82 controller: FieldCtrl,
83 bindings: {
84 ngModel: '=',
85 name: '=',
86 field: '='
87 }
88};