我在由 jquery-ui 自动完成组成的自动完成 angularjs 指令上传递动态数据时遇到问题。这是我当前的代码:
HTML:
<div ng-app="peopleApp">
<div ng-controller="indexController">
<label class="input-group-addon input-label">Search:</label>
<input class="form-control input-form" id="search" type="text" placeholder="Search here..." auto-complete names="names">
<button ng-click="change()">Change</button>
</div>
</div>
JS:
var peopleApp = angular.module('peopleApp', []);
peopleApp.controller('indexController', function($scope, $http, $rootScope, $controller){
$http.post(domainName+url)
.then(function(response){
data = response.data.data;
$scope.names = data.map(function(obj){ var rObj = []; rObj.push(obj['rank_code']); rObj.push(obj['rank_description']); return rObj; });
});
$scope.change = function(){
$scope.names = ["hnnnnn", "billlll"];
}
});
peopleApp.directive('autoComplete', function(){
return {
scope: {names: '='},
link: function(scope, element, attrs){
// alert(JSON.stringify(element));
attrs.$observe('names', function(val){
// scope.info = val;
alert(val);
scope.names = val;
});
element.autocomplete({
source: scope.names,
select: function() {
// alert('dean');
// iElement.trigger('input');
},
// Sets the min of characters before activating dropdown
minLength:2
});
}
}
});
首先,从 API 获取的数据不会集成到自动完成中。其次,我希望当我按下按钮时,将更改的 $scope.names 也将集成到自动完成中
最佳答案
使用 jQuery autocomplete
的工作解决方案。
jsfiddle 上的实例.
function DefaultCtrl($scope) {
$scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
$scope.addName = function() {
$scope.names.push($scope.name);
}
}
angular.module('MyModule', [])
.controller('DefaultCtrl',DefaultCtrl)
.directive('autoComplete', function($timeout) {
return {
restrict: "A",
scope: {
uiItems: "="
},
link: function(scope, iElement, iAttrs) {
scope.$watchCollection('uiItems', function(val) {
console.log(val);
iElement.autocomplete({
source: scope.uiItems,
select: function() {
$timeout(function() {
iElement.trigger('input');
}, 0);
}
});
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css" rel="stylesheet" type="text/css">
<div ng-app='MyModule'>
<div ng-controller='DefaultCtrl'>
<input auto-complete ui-items="names" ng-model="selected"> selected = {{selected}}
<br>
<input placeholder="add name" ng-model="name">
<button ng-click="addName()">
Add name
</button>
<pre>{{names|json}}</pre>
</div>
</div>
关于javascript - 动态自动完成指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763061/