【问题标题】:Angularjs - Access the value of dropdown in a nested ng-repeatAngularjs - 在嵌套的 ng-repeat 中访问下拉列表的值
【发布时间】:2014-11-16 14:27:02
【问题描述】:

I'm can't access the value of the select in the controller when the select is inside an ng-repeat.

这是 Html 的示例(一切正常显示):

<tr ng-repeat="reservationItem in dataList">
    <select ng-model="detail" ng-change= "haha($index)" ng-options="n for n in [1,2,3,42]" >
        <option value="Choose"> Choose </options>
    </select> 
</tr>

``

在控制器中,在函数 haha​​() 中,我尝试获取所选下拉列表的值: $scope.haha = function(index){ console.log(index); console.log($scope.detail); }

第一个 console.log 总是显示 0 第二个 console.log 总是显示 undefined

谁能告诉我如何访问嵌套在控制器中的选择值。 ? 谢谢

【问题讨论】:

  • 您的 ng-model 应该与您在 ng-repeat 中的迭代相关...reservationItem.detail 应该是它自己的参数
  • 但是在这种情况下,正如您所解释的,您如何从控制器访问值?我尝试了 $scope.reservationItem.detail 并收到一条错误消息“TypeError: Cannot read property 'reservationDetail' of undefined”。
  • reservationItem 只是您在 dataList 集合的 ng-repeat 属性中使用的别名。 $scope.dataList 是您的父对象...您将绑定到 dataList 数组成员的属性
  • 是的......并确保为您的 ng-model 使用 reservationItem.detail
  • 和 haha​​($index) 似乎为您提供了要在操作上查询的索引...传递 reservationItem 而不是 $index ,您将拥有具有所选详细信息的整个对象已加载

标签: javascript angularjs angularjs-scope


【解决方案1】:

在这种情况下,您有多个详细的 ng-model。这会混淆角度,将 ng-model 视为 ID。你不能有重复。您需要将选择拉出,或将详细信息附加到 reservationItem 即。预订项目.detail

此外,您不需要 ng-change,因为角度自动将该值绑定到模型。

【讨论】:

  • 但是在这种情况下,正如您所解释的,您如何从控制器访问值?我尝试了 $scope.reservationItem.detail 并收到一条错误消息“TypeError: Cannot read property 'reservationDetail' of undefined”。
  • reservationDetail 实际上是一个私有变量,只有函数知道。您需要在函数调用期间发送该变量。做这样的事情
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多