在AngularJS中,如何将select中的选项设置为页面上其他位置的参数?

时间:2013-09-20 16:46:10

标签: angularjs

在AngularJS中,如何从select元素中获取所选选项以将其放在页面上的其他位置?

<div class="modal-body">
    <form class="">
        <div class="control-group">
            <label class="control-label" for="role">Choose a Playlist</label>
            <div class="controls">
                <select name="playlist">
                    <option ng-repeat="playlist in playlists | orderBy: 'playlist'" value="{{playlist.id}}">{{ playlist.name }}</option>
                </select>
            </div>
        </div>
        <p>
            Or,
            <a class="branded" href="#">Create New Playlist</a>
        </p>
    </form>
</div>
<div class="modal-footer">
    <button class="btn btn-branded" ng-click="postSongToPlaylist();">Save</button>
</div>

我希望获得用户在select元素中选择的选项,并将其作为ng-click的参数。如何让Angular“知道”哪个选项是正确的?

1 个答案:

答案 0 :(得分:3)

该值将作为ng-model标记的select名称存储在范围内。

<div class="modal-body">
    <form class="">
        <div class="control-group">
            <label class="control-label" for="role">Choose a Playlist</label>
            <div class="controls">
                <select name="playlist" ng-model="playlist" ng-options="playlist.id as playlist.name for playlist in playlists | orderBy: 'playlist'">
                </select>
            </div>
        </div>
        <p>
            Or,
            <a class="branded" href="#">Create New Playlist</a>
        </p>
    </form>
</div>
<div class="modal-footer">
    <button class="btn btn-branded" ng-click="postSongToPlaylist(playlist);">Save</button>
</div>

我还建议您使用ng-options代替ng-repeat来填充选项标记。