如记录的那样,ng-options表现不如预期?

时间:2017-12-12 05:51:01

标签: angularjs angularjs-ng-options

无论我尝试什么,ID总是作为值传递。我希望Genre.label(string)作为值...

我正试图了解ng-options,我阅读了文档,示例似乎很简单,但是我得到的结果与预期不同。

我的图书模型是

Book: {
    title: string,
    genre: string,
    description: string
}

我的流派模型是

Genre: {
    label: string
    description: string
}

然后当我使用ng-init="getGenres()"将类型拉入我的范围时,我使用

进行预测
ng-options="genre.label for genre in genres track by genre.label" 

将使用LABEL进行每次迭代,并使用LABEL填充选项值,事实上 - Inspect Element确实显示了 - 它看起来像这样:

<option label="Sci-fi" value="Sci-fi">Sci-fi</option>

我的数据最终看起来像这样:

_id : 5a2f...5691
genre : "5a2f552765226c3018be9878"
title : "Blah Blah"

以下是上下文中的表单:

<form ng-submit="addBook()" ng-init="getGenres()" >
    <div class="form-group" >
        <label>Title</label>
        <input type="text" class="form-control" ng-model="book.title" placeholder="Title" >
    </div>
    <div class="form-group" >
        <label>Genre</label>
        <select class="form-control" ng-model="book.genre"
                ng-options="genre.label for genre in genres track by genre.label" >
            <option value="">-- choose genre --</option>
        </select>
    </div>
</form>

这是COLTROLLERs getGenres:

// get genres
$scope.getGenres = function() {
    $http.get('/api/genres')
    .success(function(response) {
        $scope.genres = response;
    });
}

它返回:

[{
    "_id": "5a2f5.....a065b",
    "label": "Sci-fi",
    "description": "Dealing with subject matter that combines fictional worlds and science, both real and theoretical."
}, {
    "_id": "5a2f5.....9877",
    "label": "Romance",
    "description": "Topics with amorous overtone, undertones and toneless rantings. Matters of the heart. Emotional folly and frolic."
}, {
    "_id": "5a2f5.....9878",
    "label": "Suspense",
    "description": "Events dealing with an arousal of anticipation and dread, mostly in equal parts."
}, {
    "_id": "5a2f5.....9879",
    "label": "Gobbeldegook",
    "description": "nonsensical gibberish. blather, post-moderistic drivel."
}, {
    "_id": "5a2f5.....987a",
    "label": "Drama",
    "description": "Drama Drama Drama Drama Drama Drama Drama"
}, {
    "_id": "5a2f5.....987b",
    "label": "NonFiction",
    "description": "Real life crap. No fakery or literary license, this is REAL!"
}]

非常感谢任何帮助 -cheers

1 个答案:

答案 0 :(得分:1)

你应该这样使用:

    <select class="form-control" ng-model="book.genre"
            ng-options="genre.label  as genre.label for genre in genres track by genre.label" >
        <option value="">-- choose genre --</option>
    </select>

如果您不使用genre.label as,则在这种情况下,该类型将用作模型 BEFORE as之间的表达式genre.label将用作模型值 as之后的表达式genre.label将用作选项中的显示值。