I wrote my own directive to parse a input with select2 and gat data via ajax.
HTML:
<input type="text"
ng-model="name"
data-ui-event="{keyup: 'searchByName($event)',change: 'searchByName($event)'}"
ajax-select2="single" data-url="/ajax/name/"
/>
JS:
.directive('ajaxSelect2', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var reqParams = {},
multiple = attrs.ajaxSelect2 === "multi" ||
attrs.ajaxSelect2 === "multiple" ? true : false;
switch(element.prop("tagName")) {
case 'INPUT':
element.select2({
multiple: multiple,
ajax: {
quietMillis: 200,
url: attrs.url,
dataType: 'json',
type: 'POST',
data: function (term, page) {
var req = {
"val": term,
};
return JSON.stringify(req);
},
results: function (data, page) {
return { results: data };
}
}
});
break;
default:
alert('ajax-select2 works only with input fields!');
break;
}
element.bind("change", function () {
element.show(); //shows the input
$timeout(function () {
element.trigger('keyup'); //doesn't work
});
});
}
}}])
My problem: The selected value is set to the input and the searchByName function is called, but it did not work with my ng-model. If I add another input with ng-model="name" the value should be written to this input too. But it doesn't.
EDIT : Here is a jsFiddle
Got it!
I had to update the ng-model in the scope by hand.
element.bind("change", function(e) {
scope.$apply(function() {
scope[attrs.ngModel] = e.val;
});
});
Full code example here .
Correct your code to :
$timeout(function () {
element.trigger('keyup'); //doesn't work
}, **Interval**);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.