从ng-repeat或ng-options返回对象?

时间:2014-01-14 19:10:02

标签: angularjs

好的,我有以下内容:

<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>

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

2 个答案:

答案 0 :(得分:7)

<select ng-model="item" ng-options="o as o.date for o in monthpicker(singles)">

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

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

Plunkr

答案 1 :(得分: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
}