-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathangular-query-builder.js
98 lines (83 loc) · 3.11 KB
/
angular-query-builder.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var app = angular.module('app', ['ngSanitize', 'queryBuilder']);
app.controller('QueryBuilderCtrl', ['$scope', function ($scope) {
var data = '{"group": {"operator": "AND","rules": []}}';
function htmlEntities(str) {
return String(str).replace(/</g, '<').replace(/>/g, '>');
}
function computed(group) {
if (!group) return "";
for (var str = "(", i = 0; i < group.rules.length; i++) {
i > 0 && (str += " <strong>" + group.operator + "</strong> ");
str += group.rules[i].group ?
computed(group.rules[i].group) :
group.rules[i].field + " " + htmlEntities(group.rules[i].condition) + " " + group.rules[i].data;
}
return str + ")";
}
$scope.json = null;
$scope.filter = JSON.parse(data);
$scope.$watch('filter', function (newValue) {
$scope.json = JSON.stringify(newValue, null, 2);
$scope.output = computed(newValue.group);
}, true);
}]);
var queryBuilder = angular.module('queryBuilder', []);
queryBuilder.directive('queryBuilder', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
group: '='
},
templateUrl: '/queryBuilderDirective.html',
compile: function (element, attrs) {
var content, directive;
content = element.contents().remove();
return function (scope, element, attrs) {
scope.operators = [
{ name: 'AND' },
{ name: 'OR' }
];
scope.fields = [
{ name: 'Firstname' },
{ name: 'Lastname' },
{ name: 'Birthdate' },
{ name: 'City' },
{ name: 'Country' }
];
scope.conditions = [
{ name: '=' },
{ name: '<>' },
{ name: '<' },
{ name: '<=' },
{ name: '>' },
{ name: '>=' }
];
scope.addCondition = function () {
scope.group.rules.push({
condition: '=',
field: 'Firstname',
data: ''
});
};
scope.removeCondition = function (index) {
scope.group.rules.splice(index, 1);
};
scope.addGroup = function () {
scope.group.rules.push({
group: {
operator: 'AND',
rules: []
}
});
};
scope.removeGroup = function () {
"group" in scope.$parent && scope.$parent.group.rules.splice(scope.$parent.$index, 1);
};
directive || (directive = $compile(content));
element.append(directive(scope, function ($compile) {
return $compile;
}));
}
}
}
}]);