angularjs
  • jquery-ui
  • angularjs-directive
  • angularjs-scope
  • jquery-autocomplete
  • 2015-02-05 50 views 0 likes 
    0

    我發現很好的在AngularJS here on GitHub中包裝jQuery datepicker的工作實現,然後試圖用jQuery Autocomplete完成相同的工作。在AngularJS中包裝jQuery自動完成

    的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字段根本!

    更有趣的是,在ngModel.$viewValue初始化控制器與一些預定義的currentSuggestion$scope.currentSuggestion = 'Java';結果是在$渲染方法undefined

    這裏是一個plunkr

    有人能解釋我爲什麼這樣的表現和糾正我的錯誤?

    回答

    0

    我想是因爲$ parent.scope沒有「currentSuggestion」實施,因此變得不確定,而這應該工作,因爲它從電流控制範圍得到的值:

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

    相關問題