ng-model is not updating when using jquery element.val()

后端 未结 4 1332
天命终不由人
天命终不由人 2020-12-18 09:09

PLUNKR example here

I\'m using some version of jquery autocomplete as an angularjs direcitve. When the jquery updates the input\'s value using element.val()

4条回答
  •  失恋的感觉
    2020-12-18 09:37

    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);
            }
        }
    });
    

提交回复
热议问题