我想做一个简单的“自动完成”。在输入中输入关键字并选择结果。然后将显示所选项目。我目前正在坚持如何更改隐藏的select
并显示所选项目。你能帮帮我吗?
<div ng-controller="MyCtrl">
<input type="search" ng-model="query">
<ul ng-repeat="game in games | filter:query" ng-show="query.length >= 2 && (games | filter:query).length">
<li><a ng-click="selectGame(game.id)">{{ game.name }}</a></li>
</ul>
<select multiple name="games" style="display:none;" ng-options="game.id as game.name for game in games"></select>
<ul class="selected-games">
<li>{{ game.name }} - {{ game.year }}</li>
</ul>
</div>
<script type="text/javascript">
function MyCtrl($scope, $http) {
$http.get('/ajax/all/games/').success(function(data){
$scope.games = data;
});
$scope.selectGame = function() {}; //?
}
//MyCtrl.$inject = ['$scope', '$http'];
// JSON data from URL
var games = [
{'id': 1, 'name': 'Halo', 'year': '2005'},
{'id': 2, 'name': 'Final Fantasy', 'year': '2008'},
{'id': 3, 'name': 'Guitar Heroes', 'year': '2008'},
{'id': 4, 'name': 'Warcraft', 'year': '2003'},
{'id': 5, 'name': 'Starcraft II', 'year': '2010'},
{'id': 6, 'name': 'Fifa 12', 'year': '2012'},
];
</script>
答案 0 :(得分:0)
很难理解您想要的结果,但请查看我的更新:http://jsfiddle.net/rS6Hz/1/。我在scope
添加了一个新变量,一个名为selectedGames的数组,并通过添加到该数组来实现ng-click。
$scope.selectedGames = [];
$scope.selectGame = function(game) {
$scope.selectedGames.push(game);
};
然后,在显示屏中,您必须向ng-model
添加select
才能执行任何操作(据我所知)和ul
selected-games
需要ng-repeater
来循环selectedGames
<select multiple name="games" ng-model="something" ng-options="game.id as game.name for game in selectedGames"></select>
<h1>Selected Games</h1>
<ul class="selected-games">
<li ng-repeat="game in selectedGames">{{ game.name }} - {{ game.year }}</li>
</ul>
(我删除了display: none;
上的select
以便查看。
答案 1 :(得分:0)
这是另一种方法,不使用单独的变量:
基本上:
<ul class="selected-games">
<li ng-repeat='game in games | filter:{selected:true}'>{{ game.name }} - {{ game.year }}</li>
</ul>
我认为这是一个比公认的更清洁的解决方案