I'm trying to deal with different behavior of ngModel
in different browsers.
My directive wraps jqueryUI autocomplete and on its select
event it calls ngModel.$setViewValue(selectedItem.id)
. Autocomplete allows user to select item by mouse click or by pressing enter
on the keyboard.
If suggested item is:
{
"name": "Apple",
"id": "1000"
}
I expect after selecting it, the ngModel value will be selected item's id
- 1000
.
In Chrome it works OK - it sets $viewValue
and $modelValue
correctly ($modelValue=1000
).
In Firefox it sets model as in Chrome ($modelValue=1000
), but when I click somewhere else - make blur (then browser probably fires change
event), model changes and it becomes same as visible input value ($modelValue='Apple'
).
In IE 11 it sets model correct only when I select item with mouse click. If I select it by pressing enter
, the model becomes visible input value ($modelValue='Apple'
)
Here is plunkr: http://plnkr.co/edit/o2Jkgprf8EakGqnpu22Y?p=preview
I'd like to reach the same behavior in every browser. How to deal with that problems?
This seems to be related to http://bugs.jqueryui.com/ticket/8878
As pointed out in the above link, the change event is triggered only in Firefox and not in Chrome. So in your case, $setViewValue is again triggered when clicked outside and the model value is set to "Apple".
There is change callback for autocomplete jquery ui widget. To handle both the case/browsers may be you would have to explicitly set view value again on this call back (and it works).
http://plnkr.co/edit/GFxhzwieBJTSL8zjSPSZ?p=preview
link: function(scope, elem, attrs, ngModel) {
elem.on('change', function(){
// This will not be printed in Chrome and only on firefox
console.log('change');
});
select: function(event, ui) {
ngModel.$setViewValue(ui.item.data.id);
scope.$apply();
},
// To handle firefox browser were change event is triggered
// when clicked outside/blur
change: function(event, ui) {
ngModel.$setViewValue(ui.item.data.id);
scope.$apply();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With