-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathem-autocomplete.directive.js
57 lines (48 loc) · 1.9 KB
/
em-autocomplete.directive.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
angular.module('portal-components')
.directive('emAutocomplete', function() {
return {
restrict: 'E',
template: '<div style="position:relative"><input type="text" autocomplete="off" ng-model="value" ng-blur="onBlur($event)" placeholder="{{ placeholder }}" typeahead="value[displayKey || \'name\'] for value in getOptions($viewValue)" typeahead-editable="false" typeahead-on-select="selectOption($item)" typeahead-wait-ms="300" class="form-control"/><div ng-show="value" class="em-clear-button"><a ng-click="clear($event)"><span class="glyphicon glyphicon-remove"></span></a></div></div>',
scope: {
model: '=emModel',
placeholder: '@emPlaceholder',
apiResource: '&emApiResource',
queryParams: '=emQueryParams',
displayKey: '@emDisplayKey',
queryKey: '@emQueryKey'
},
link: function(scope, element, attrs) {
scope.value = undefined;
scope.getOptions = function(query) {
var params = scope.queryParams ? angular.copy(scope.queryParams) : {};
params[scope.queryKey || 'name'] = query;
params.sort = name;
return scope.apiResource().query(params).then(function(res) {
return res.data;
});
};
scope.selectOption = function(option) {
scope.model = option ? option._id : undefined;
};
scope.clear = function(event) {
event.preventDefault();
event.stopPropagation();
scope.selectOption(undefined);
scope.value = undefined;
};
scope.onBlur = function(event) {
if (!scope.value) {
event.target.value = '';
scope.model = undefined;
}
return true;
};
scope.$watch('model', function(newModel, oldModel) {
if (scope.value || !newModel) return;
scope.apiResource().get(scope.model).then(function(resource) {
scope.value = resource;
});
});
}
};
});