Problems with jQuery autocomplete + AngularJS

后端 未结 3 1959
夕颜
夕颜 2020-12-02 11:35

i\'m using AjgularJS on my page and want to add a field to use autocomplete from jqueryui and the autocomplete does not fires the ajax call.

i\'ve tested the script

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 12:02

    Perhaps you just need to do it in an "angular way"... that is, to use a directive to set up your DOM elements and do event bindings, use a service to get your data, and use a controller to do your business logic... all while leveraging the dependency injection goodness that is Angular...

    A service to get your autocomplete data...

    app.factory('autoCompleteDataService', [function() {
        return {
            getSource: function() {
                //this is where you'd set up your source... could be an external source, I suppose. 'something.php'
                return ['apples', 'oranges', 'bananas'];
            }
        }
    }]);
    

    a directive to do the work of setting up the autocomplete plugin.

    app.directive('autoComplete', function(autoCompleteDataService) {
        return {
            restrict: 'A',
            link: function(scope, elem, attr, ctrl) {
                        // elem is a jquery lite object if jquery is not present,
                        // but with jquery and jquery ui, it will be a full jquery object.
                elem.autocomplete({
                    source: autoCompleteDataService.getSource(), //from your service
                    minLength: 2
                });
            }
        };
    });
    

    And using it in your markup... notice the ng-model to set a value on the $scope with what you select.

    Foo = {{foo}}

    That's just the basics, but hopefully that helps.

提交回复
热议问题