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

后端 未结 4 1333
天命终不由人
天命终不由人 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:57

    I don't recommend updating the plugin itself you can change your directive instead to something like this..

    app.directive("autoComplete", function() { 
        return {
            restrict : "A" , 
            require  : '^ngModel', 
            scope    : 
            {
                ngModel: '=',
                AutoCompleteOptions : "&autoCompleteOptions"
            },
            link     : function (scope, element, 
                    // prevent html5/browser auto 
                    attrs.$set('autocomplete','off');
                    var options = scope.
                    options.onSelect = function(elem) {
                         scope.$apply(function() {
                             scope.ngModel = elem.value;
                         });
                    };
                scope.autocomplete = $(element).autocomplete(scope.AutoCompleteOptions());
            }
        }
    });
    

    As you've noticed in the scope object initialization of the directive I have selected the ngModel attribute as something to be used by the onSelect event of the AutoComplete Jquery Plugin, where I have updated the model using the scope.$apply() method. Use scope.$apply in a directive so that the scope.$digest() will be invoked and have the model affected directly.

提交回复
热议问题