blob: 89fdd761b36d3c7455ce473cc53b2164c36fbd42 [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)
60 if (this.field.default && !angular.isDefined(this.ngModel)) {
61 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};