forked from Siyfion/angular-typeahead
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-typeahead.js
50 lines (45 loc) · 1.66 KB
/
angular-typeahead.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
angular.module('siyfion.sfTypeahead', [])
.directive('sfTypeahead', function () {
return {
restrict: 'ACE',
scope: {
datasets: '=',
ngModel: '='
},
link: function (scope, element) {
element.typeahead(scope.datasets);
// Updates the ngModel binding when a value is manually selected from the dropdown.
// ToDo: Think about how the value could be updated on user entry...
element.bind('typeahead:selected', function (object, datum, dataset) {
scope.$apply(function() {
scope.ngModel = datum;
scope.selectedDataset = dataset;
});
});
// Updates the ngModel binding when a query is autocompleted.
element.bind('typeahead:autocompleted', function (object, datum, dataset) {
scope.$apply(function() {
scope.ngModel = datum;
scope.selectedDataset = dataset;
});
});
// Updates typeahead when ngModel changed.
scope.$watch('ngModel', function (newVal) {
if ($.isArray(scope.datasets)) {
for (var i=0;i<scope.datasets.length;i++) {
if (scope.datasets[i].name == scope.selectedDataset) {
var valueKey = scope.datasets[i].valueKey;
break;
}
}
} else {
var valueKey = scope.datasets.valueKey;
}
if (newVal && valueKey && newVal.hasOwnProperty(valueKey)) {
newVal = newVal[valueKey];
}
element.typeahead('setQuery', newVal || '');
});
}
};
});