我發現很好的在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
有人能解釋我爲什麼這樣的表現和糾正我的錯誤?