我是 AngularJS 的新手,我正试图以最优雅的方式解决一个问题。
我有来自服务器的列表,并在我的应用程序中用作select标记的来源。option让我们假设它是一个作者列表,如下所示:
[
{ id: 1, name: 'Mark Twain' },
{ id: 2, name: 'Jack London' },
{ id: 3, name: 'Ernest Hemingway' }
]
我也有书籍模型,它来自并保存到服务器。书籍的属性之一是author用户可以从select下拉列表中选择。当书籍模型被保存或从服务器获取时,它的author字段表示为整数。以下是如何将书籍模型保存在服务器上以及获取时的外观示例:
{
id: 324,
title: 'Martin Eden',
author: 2
}
book在我的应用程序中表示为 Angular $resource,因此每当我想保存 book 模型时,我只需将其称为 save 方法。
为了实现这个逻辑,我尝试使用selectwithng-options指令,如下所示:
<select ng-options="author as author.name for author in authors track by author.id" ng-model="bookModel.author"></select>
但是这种方法的问题是,当我从下拉列表中选择作者时,author属性的值设置为,{ id: 2, name: 'Jack London' }但我需要它是作者的 ID。
这是一个说明我的问题的小提琴。尝试在下拉列表中选择不同的值。在下拉列表下方,您将看到 的更新值bookModel.author。我需要它是作者的 id 整数,而不是对象。因此,每当我在下拉菜单中选择Jack LondonbookModel.author时,我都需要to be的值,2而不是{ id: 2, name: 'Jack London' }。否则,每当书籍模型来自服务器时以及在保存之前,我都需要对数据进行操作。我想可能有更好的方法。也许这是可以通过ng-options指令实现的?
我试过这样做:
<select ng-model="bookModel.author">
<option ng-repeat="author in authors" value="{{author.id}}">{{author.name}}</option>
</select>
它有点接近,但这种方式bookModel.author的值将是一个字符串,而不是整数。
我也知道我可以为 book $resource 设置transformRequest和transformResponse函数,它将数据转换为适当的格式。但也许有更好的方法?
将不胜感激任何帮助!