2014-11-06 43 views
1

從文檔:如何選擇在ng-tags-input自動填充中顯示哪個字段?

<tags-input> 
    <auto-complete 
    source="{expression}" 
    > 
    </auto-complete> 
</tags-input> 

的表達式的結果必須是一個承諾,最終解析爲對象的數組。

$scope.loadSuperheroes = function(query) { 
// An arrays of strings here will also be converted into an 
// array of objects 
return $http.get('superheroes.json'); 
}; 

但我已經有$ scope中的對象數組。但具有不同的結構:

$scope.superheroes = [{"id":1, "name":"Batman"}, {"id":2, "name":"Superman"}] 

如何在HTML中使用列表從$ scope.superheroes.name說?

回答

1

如在文檔中描述:http://mbenford.github.io/ngTagsInput/gettingstarted

NgTagsInput可以基本項目(我問GitHub上到該指令個月前的創造者)的磁盤陣列上執行自動完成。

所以我會認爲你將擁有:

  1. 重建你的對象的數組像這樣[{ text: 'Tag1' }, { text: 'Tag2' }, { text: 'Tag3' }]
  2. 然後,您必須使用$查詢爲您loadSuperheroes的參數()方法(如$查詢是正在鍵入的文本

所以,HTML:

<tags-input ng-model="filteredsuperheroes"> 
<auto-complete 
    source="loadSuperheroes($query)" 
    > 
    </auto-complete> 
</tags-input> 

然後,JS(角)部分:

$scope.filteredsuperheroes = []; 
angular.forEach(superheroes, function(superhero) { 
    var newEntry = {}; 
    newEntry['text'] = superhero.name; 
    $scope.filteredsuperheroes.push(newEntry); 
}); 
$scope.loadSuperheroes = function(query) { 
    return $http.get('/filteredsuperheroes?query=' + query); 
}; 

提供一個活生生的例子,所以我可以測試這個:)我不知道,將工作,但你應該很容易理解我的意思:)

+0

我明白你的意思。但我正在尋找不創建額外的$ scope.filteredsuperheroes的方式。只要使用現有的$ scope.superheroes – AngryDev 2014-11-06 14:21:12

+0

好的,有什麼理由呢? – enguerranws 2014-11-06 15:59:10

+0

:-)沒有理由 - 只是尋找最好的方式 – AngryDev 2014-11-06 17:31:39

3

您可以更改通過設置displayProperty屬性顯示標籤文本屬性:

<tags-input ng-model="tags" display-property="name"></tags-input> 

該屬性也將是我們由autocomplete指令編輯以顯示返回的建議。

0

自動完成的源屬性需要承諾,所以如果你想使用一個已經存在的對象的數組,你必須返回解析爲它的承諾:

$scope.superheroes = [{"id":1, "name":"Batman"}, {"id":2, "name":"Superman"}]; 

    $scope.loadTags = function(query) { 
    var deferred = $q.defer(); 
    deferred.resolve($scope.superheroes); 
    return deferred.promise; 
    }; 

和,如您在顯示屬性名稱不文本(由tagsInput默認),您需要通過添加屬性顯示屬性=「名稱」到標籤,輸入元素,將其指定:

<tags-input ng-model="superheroesModel" display-property="name" add-on-paste="true"> 
     <auto-complete min-length="1" source="loadTags($query)"></auto-complete> 
</tags-input> 

我從ngTagsInput Demo Page分叉了一個簡單的自動完成示例並做出了這些更改。看看這些變化here

相關問題