您好,
我正在构建一个自动完成指令,我需要在同一表单中的两个位置。自动完成功能工作正常,但它在两个地方都显示相同的指令。我已经附加了一个带有这个问题的图像,即使我输入了一个国家/地区,自动完成也被激活了,如何将其绑定到用户正在进行交互的元素?
以下是我的指令代码
angular.module('xyz').directive('autoComplete',['$rootScope',function($rootScope){
return {
restrict:'AE',
transclude: true,
replace: true,
scope:{
selectedTags:'=model',
userdata:'=',
name:'@'
},
templateUrl: function(elem,attr){ return 'views/rad/layout/autocomplete.html' },
link:function(scope,elem,attrs){
scope.suggestions=[];
scope.selectedTags=[];
scope.selectedIndex=-1; //currently selected suggestion index
scope.search=function(){
var newSuggestions = [];
// if(attrs.userdata.indexOf(scope.searchText)===-1){
// //dataUser.unshift(scope.searchText);
// }
for(var i=0; i < scope.userdata.length;i++)
{
if(dataUser[i].toLowerCase().indexOf(scope.searchText.toLowerCase()) !== -1){
newSuggestions.push(dataUser[i]);
}
}
scope.suggestions = newSuggestions;
scope.selectedIndex = -1;
}
scope.checkKeyDown=function(event){
console.log(event.keyCode);
if(event.keyCode===40){//down key, increment selectedIndex
event.preventDefault();
if(scope.selectedIndex+1 !== scope.suggestions.length){
scope.selectedIndex++;
}
}
else if(event.keyCode===38){ //up key, decrement selectedIndex
event.preventDefault();
if(scope.selectedIndex-1 !== -1){
scope.selectedIndex--;
}
}
else if(event.keyCode===13){ //enter pressed
scope.addToSelectedTags(scope.selectedIndex);
}
}
scope.addToSelectedTags=function(index){
if(scope.selectedTags.indexOf(scope.suggestions[index])===-1){
scope.selectedTags.push(scope.suggestions[index]);
scope.searchText='';
scope.suggestions=[];
}
}
scope.$watch('selectedIndex',function(val){
if(val!==-1) {
scope.searchText = scope.suggestions[scope.selectedIndex];
}
});
scope.removeTag=function(index){
scope.selectedTags.splice(index,1);
}
}
}
}])
以下是自动完成模板
<div class="tags-wrapper">
<div id="tagsList" class="tags-cloud">
<div class="suggestionListing">
<div ng-repeat="selectedTag in selectedTags track by $index" class="tag">
<span class="tagName">{{selectedTag}}</span>
<span> <b ng-click="removeTag($index)" class="fa fa-times cross"></b></span>
</div>
</div>
<div class="input-group">
<input type="text" name="{{inputname}}"placeholder="" aria-describedby="basic-addon2" id="searchInput" class="form-control no-border" ng-model="searchText" ng-keydown="checkKeyDown($event)" class="form-control" ng-model="searchText" ng-change="search()"/>
<div class="suggestions-list">
<div ng-repeat="suggestion in suggestions track by $index" class="blockSpan" ng-click="addToSelectedTags($index)" ng-mouseover="$parent.selectedIndex=$index" ng-class="{active : selectedIndex===$index}">
<div class="userAvatar">
<i class="fa fa-user"></i>
</div>
<div class="userInfo">
{{suggestion}}
</div>
<br clear="all" />
</div>
</div>
</div>
</div>