在AngularJS中包装jQuery自动完成

时间:2015-02-05 14:55:59

标签: angularjs jquery-ui angularjs-directive angularjs-scope jquery-autocomplete

我发现在AngularJS here on GitHub中包装jQuery datepicker的工作实现很好,然后尝试使用jQuery Autocomplete执行相同的操作。

的index.html:

<body ng-app="myApp" ng-controller="testCntrl">
    <input type='text' autocomplete ng-model='$parent.currentSuggestion' static-data='staticData' select=inform(suggestion) /><br />
    Current Suggestion - {{currentSuggestion}}
    <script type="text/javascript" src="autocomplete.js"></script>
    <script type="text/javascript" src="app.js"></script>
</body>

app.js

angular.module('myApp', ['myApp.directives']).controller('testCntrl', function ($scope) {    
    $scope.currentSuggestion = '';    
    $scope.staticData = ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"];    
    $scope.inform = function (suggestion) {
        console.log(suggestion);
    };
});

和autocomplete.js

angular.module('myApp.directives', []).directive('autocomplete', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        scope: {
            select: '&',
            data: '=staticData'
        },
        link: function (scope, element, attrs, ngModel) {
            if (!ngModel) {
                return;
            }
            var updateModel = function (suggestion) {
                scope.$apply(function () {
                    ngModel.$setViewValue(suggestion);
                });
            };
            var options = {};
            options.minLength = 1;
            options.source = scope.data;
            options.select = function (event, ui) {
                updateModel(ui.item.value);
                if (scope.select) {
                    scope.$apply(function () {
                        scope.select({ suggestion: ui.item.value });
                    });
                }
            };
            ngModel.$render = function () {
                element.val(ngModel.$viewValue);
            };
            element.autocomplete(options);
        }
    };
});

在我的情况下,这一行ngModel.$setViewValue(suggestion);根本不会更新currentSuggestion字段!

更有趣的是,使用currentSuggestion之类的预定义$scope.currentSuggestion = 'Java';初始化控制器会导致{render}方法中的ngModel.$viewValueundefined

这是plunkr

有人可以解释一下为什么它会像这样表现并纠正我的错误吗?

1 个答案:

答案 0 :(得分:0)

我认为因为$ parent.scope没有&#39; currentSuggestion&#39;实现,因此它变得未定义,而这应该工作,因为它从当前控制器范围获取值:

<input type='text' autocomplete ng-model='currentSuggestion'