AngularJS - 更新多个选择的选定选项

时间:2012-12-01 05:10:20

标签: angularjs

我想做一个简单的“自动完成”。在输入中输入关键字并选择结果。然后将显示所选项目。我目前正在坚持如何更改隐藏的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>

2 个答案:

答案 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)

这是另一种方法,不使用单独的变量:

http://jsfiddle.net/9Ag9r/

基本上:

 <ul class="selected-games">
        <li ng-repeat='game in games | filter:{selected:true}'>{{ game.name }} - {{ game.year }}</li>
 </ul>

我认为这是一个比公认的更清洁的解决方案