【问题标题】:returning object from ng-repeat or ng-options?从 ng-repeat 或 ng-options 返回对象?
【发布时间】:2014-01-15 03:40:00
【问题描述】:

好的,我有以下内容:

<select ng-model="item" ng-change="monthpickerclick()">
<option  class="animate-repeat" ng-repeat="returnpicker in monthpicker(singles)" value="{{returnpicker.date}}">{{returnpicker.date}}</option>
</select>

每个选项都有一个像这样的对象:

returnpicker: Object
$$hashKey: "02O"
Year: 2014
dailyPrice: "165"
date: "January-2014"
minimumStay: 5
month: 0
monthlyPrice: "4000"
reserved: false
weeklyPrice: "880"

从我的控制器中选择时,如何获取每个选项的对象值? 目前是这样的:

scope.$watch('item', function(){
   console.log(scope.item);
});

返回选项字符串值,但我还需要获取月份和年份? 如何???

我也试过了:

<select ng-model="item" ng-options="o.month as o.month for o in monthpicker(singles)" ng-click="monthpickerclick()">{{item}}</select>

但这会从选项中删除对象中的所有其他值。

【问题讨论】:

  • 你能组装一个 jsFiddle 吗?
  • 正在努力!目前数组有点大,js文件超过2000行..
  • 见下文。您可以在 options 标签内的任何位置访问 returnpicker 的所有属性。

标签: angularjs


【解决方案1】:
<select ng-model="item" ng-options="o as o.date for o in monthpicker(singles)">

ng-model 使用来自ng-optionso 将所选选项链接到$scope.item。 在ng-options 中,as 子句将显示的值设置为o.date

如果monthpicker(singles) 返回一个对象数组,item 将被设置为选定对象。

Plunkr

【讨论】:

  • 你是我所需要的明星!!!我一直在和这个战斗!!
  • 原则上看起来很简单!
  • 我一遍又一遍地看它,无法弄清楚我以前怎么没有看到它如此简单和如此优雅!
  • 是的,只需在其中添加一个常规的旧选项标签,其中包含您想要的默认值。 &lt;option value=""&gt;default&lt;/option&gt;。无论出于何种原因,value="" 都是必需的。我更新了 plunkr。如果这不是你的意思,请告诉我。祝你好运。
  • 哦,在这种情况下,只需将控制器中的scope.item设置为第一个或默认选择的任何一个即可。
【解决方案2】:

怎么样:

<select ng-model="item" ng-change="monthpickerclick()">
    <option  class="animate-repeat" ng-repeat="returnpicker in monthpicker(singles)" value="{{returnpicker.date}}">{{returnpicker.date}} {{returnpicker.month}} {{returnpicker.year}}</option>
</select>

编辑: 如果您的选项标签如下所示:

<option ng-click="monthpickerclick()" > ... </option>

将monthpickerclick()更改为:monthpickerclick(returnpicker),并将对象输入到函数中,因此将其保存到变量中。

<option ng-click="monthpickerclick(returnpicker)" > ... </option>

$scope.monthpickerclick(returnpicker){
    $scope.selectedReturnPicker = returnpicker; //save the object
    //other stuff
}

【讨论】:

  • 是的,但我需要来自 ng-repeat 之外的 returnpicker 的属性
猜你喜欢
  • 1970-01-01
  • 2018-05-12
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多