I'd like to make a simple "autocomplete". Enter keyword into input and select the result. Then the selected items will be shown. I'm currently stucking in how to change the hidden select
and show selected items. Could you help me?
<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>
Its hard to understand what your desired result is, but check out my updates here: http://jsfiddle.net/rS6Hz/1/. I added a new variable to the scope
, an array called selectedGames and implemented the ng-click by adding to that array.
$scope.selectedGames = [];
$scope.selectGame = function(game) {
$scope.selectedGames.push(game);
};
Then, in the display, you have to add an ng-model
to the select
for it to do anything (as far as I can tell) and the ul
of selected-games
needs an ng-repeater
to loop over the 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>
(I removed the display: none;
on the select
in order to see it.
Here is another way, without using a separate variable:
Basically:
<ul class="selected-games">
<li ng-repeat='game in games | filter:{selected:true}'>{{ game.name }} - {{ game.year }}</li>
</ul>
I believe it is a cleaner solution than the accepted one