使用jQuery element.val时(NG-模型没有更新) [英] ng-model is not updating when using jquery element.val()
问题描述
我使用jQuery自动完成的某些版本中作为一个angularjs direcitve。
当使用jQuery的更新输入值 element.val()
角确实没有通知的改变,直到之后的下一个摘要(我想)。
I'm using some version of jquery autocomplete as an angularjs direcitve.
When the jquery updates the input's value using element.val()
angular does no notice the change until after the next digest ( i suppose ).
我首先想到的是执行上的 NG-模型中的作用
后消化使用 $超时
但你可以看到它并没有帮助。
My first thought was to perform the action on the ng-model
post digest using $timeout
but as you can see it didn't help.
我的第二个方法是覆盖该元素的 VAL
函数来触发输入
事件,但我haven`t管理使它工作。
My second approach was to override the element's val
function to trigger an input
event but I haven`t managed to make it work.
尝试选择从自动完成列表中的值,你会看到,上面的NG-模型没有更新。
Try to select a value from the autocomplete list and you'll see that the ng-model above is not updating.
更新
感谢您的答复。我不知道有关 ONSELECT
选项。
Thanks for the response. I didn't know about the onSelect
option.
这是code根据您的建议
This is the code based on your recommendations
// clone user provided options
scope.options = _.extend({}, scope.AutoCompleteOptions());
// Wrap onSelect - Force update before manipulation on ng-model
var fn = _.has(scope.AutoCompleteOptions(), 'onSelect') ? scope.AutoCompleteOptions().onSelect : _.noop;
scope.options.onSelect = function () {
ngModelCtrl.$setViewValue(element.val());
scope.$apply(fn);
};
scope.autocomplete = $(element).autocomplete(scope.options);
这种方式,我保持指令的接口,而中保证了 NG-模型
将是最新的。
感谢。
推荐答案
当你已经知道,这个问题的角度不知悉的jQuery插件所做的更新。幸运的是,你可以使用插件的 ONSELECT
回调更新ngModel,像这样的:
As you already knew, the problem is angular doesn't aware of the update made by jquery plugin. Luckily, you can use the plugin's onSelect
callback to update ngModel, like this:
.directive("autoComplete", function() {
return {
restrict: "A" ,
require: 'ngModel', // require ngModel controller
scope: {
AutoCompleteOptions : "=autoCompleteOptions", // use '=' instead of '&'
},
link: function (scope, element, attrs, ngModelCtrl) {
// prevent html5/browser auto completion
attrs.$set('autocomplete','off');
// add onSelect callback to update ngModel
scope.AutoCompleteOptions.onSelect = function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(element.val());
});
};
scope.autocomplete = $(element).autocomplete(scope.AutoCompleteOptions);
}
}
});
这篇关于使用jQuery element.val时(NG-模型没有更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!