1

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

2 回答 2

0

很难理解您想要的结果是什么,但请在此处查看我的更新:http: //jsfiddle.net/rS6Hz/1/scope我向名为 selectedGames 的数组添加了一个新变量,并通过添加到该数组来实现 ng-click。

$scope.selectedGames = [];

$scope.selectGame = function(game) {
    $scope.selectedGames.push(game);        
};

然后,在显示中,您必须添加一个ng-modelselect它以执行任何操作(据我所知)并且ulofselected-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

于 2012-12-02T17:44:03.247 回答
0

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

http://jsfiddle.net/9Ag9r/

基本上:

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

我相信这是一种比公认的更清洁的解决方案

于 2013-11-22T16:49:15.673 回答