forked from Anthropic/angular-schema-form-calculate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
angular-schema-form-calculate.js
82 lines (77 loc) · 2.78 KB
/
angular-schema-form-calculate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* I calculate a field value based on a provided mathematical string
*
* @example
* {
* "type":"calculate",
* "key":"my.result",
* "watch":["product.license.basic","product.license.unified"],
* "calculate":"model.product.license.basic + model.product.license.basic / 2 * ( model.product.license.unified / 2)"
* }
*/
angular
.module('schemaForm')
.run(["$templateCache", function($templateCache) {
// A template to use
$templateCache.put('calculated-fields.html','<span class="calculate" model="model" form="form"></span>');
}])
.directive('calculate', ['$compile', '$http', 'sfBuilder', 'sfSelect', '$interpolate', 'schemaFormDecorators',
function($compile, $http, sfBuilder, sfSelect, $interpolate, schemaFormDecoratorsProvider) {
return {
restrict: 'C',
scope: {
form: '=',
model: '='
},
link: function(scope, element, attrs) {
var watchKeys = scope.form.watch,
key,
i;
scope.form.format = scope.form.format || 'number';
for (i=0; i < watchKeys.length; i++) {
key = watchKeys[i];
scope.$watch('model.'+key, function (val, old) {
var newValue = $interpolate('{{'+scope.form.calculate+'}}', false, null, true)(scope.model);
if(scope.form.lookup) {
scope.model.calculated = encodeURIComponent(newValue);
var lookup = $interpolate(scope.form.lookup, false, null, true)(scope.model);
$http.get(lookup, { responseType: 'json' })
.success(function(response, status) {
if(response.data) update(response.data);
})
.error(function(data, status) {
scope.form.options = [];
scope.form.selectedOption = '';
});
}
else {
update(newValue);
};
function update(value) {
if(scope.form.format == 'number') {
value = Number(value);
sfSelect(scope.form.key, scope.model, value);
}
else if (scope.form.format == 'string') {
sfSelect(scope.form.key, scope.model, value);
}
};
});
}
}
};
}
])
.config(['schemaFormProvider', 'schemaFormDecoratorsProvider', 'sfPathProvider',
function(schemaFormProvider, schemaFormDecoratorsProvider, sfPathProvider) {
schemaFormDecoratorsProvider.addMapping(
'bootstrapDecorator',
'calculate',
'calculated-fields.html'
);
schemaFormDecoratorsProvider.createDirective(
'calculate',
'calculated-fields.html'
);
}
]);