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.Then, in the display, you have to add an
ng-modelto theselectfor it to do anything (as far as I can tell) and theulofselected-gamesneeds anng-repeaterto loop over theselectedGames(I removed the
display: none;on theselectin order to see it.