在控制器中获取$ index的ng-repeat数量

问题描述 投票:0回答:1

我有1 ng-repeat和ng-change上的输入字段:

$scope.roomsHotel = '',
$scope.roomsOption = ['1','2','3','4','5']
$scope.numberRoom = function(index){
  $scope.roomCount =this.roomsHotel
}

并在视图中由$index重复该轨道:

<div class="row" ng-repeat="rooms in roomsOption | limitTo: roomCount track by $index">

在这个ng-repeat中我有一些md-select我需要在提交之前验证:

<div>
  <md-input-container class="md-block col-md-12" flex>
    <label>Bed Type </label>
    <md-select 
      ng-model="bedType[$index]"
      name="bedType{{$index}}"
      ng-required="true"
      ng-change="bed()">
      <md-option 
        ng-repeat="bed in bedOption" 
        ng-model="bedHotel"
        ng-value="bed"
        ng-messages>{{bed}}
      </md-option>
    </md-select>
    <div
      ng-messages="hotelForm['bedType'+$index].$error"
      ng-if="hotelForm['bedType'+$index].$invalid &&
        (submitted || hotelForm['bedType'+$index].$touched)">
      <div ng-message="required">Type of bed is require</div>
    </div>
  </md-input-container>
</div>

对于ng-message它没有问题我可以使它工作,但在控制器上我需要在提交之前验证但bedType0bedType1等等给我undefined:

$scope.submitHotelsCtrl = function( numberOfRooms, bedType,$index) {
  $scope.submitted = true;
  if ($scope.hotelForm.numberOfRooms.$valid &&
    $scope.hotelForm.bedType.$$rawModelValue.$valid) {
    console.log('hi')}
  }

我尝试循环投掷roomsOption或其他方式但非他们的工作,这里是我尝试在plnkr任何帮助将节省我的一天

javascript angularjs angular-material
1个回答
0
投票

您在plunker中提供的代码中几乎没有问题,

1)你的submitHotelsCtrl函数需要一些参数,但你没有发送任何参数,你应该至少将$ index传递给你的函数,因为你在那里使用它。

HTML

<md-button class="md-accent md-raised" ng-click="submitHotelsCtrl($index)" id="submit" >search</md-button>

JS

$scope.submitHotelsCtrl = function(index) {
}

2)即使你发送$ index因为你的按钮超出了ng-repeat $ index的范围也是未定义的,所以你应该在ng-repeat中移动你的按钮或使用其他数字。

<div class="row" ng-repeat="rooms in roomsOption | limitTo: roomCount track by $index">
    <md-button class="md-accent md-raised" ng-click="submitHotelsCtrl($index)" id="submit" >search</md-button>    
</div>

3)您应该更改您尝试按名称获取财产的代码

$scope.hotelForm.bedType$index.$valid

$scope.hotelForm['bedType'+index].$valid
© www.soinside.com 2019 - 2024. All rights reserved.