在AngularJS中为ng-model创建动态名称

时间:2014-08-27 11:56:05

标签: javascript html angularjs angular-ngmodel

问题 -

ng-model不是动态创建的。我的输入框是动态创建的,我正在尝试创建ng-model动态广告,例如test[1]test[2]等,但是当我发出表单时,我只会获取所有输入的test[shiftnumber]元件。

HTML代码 -

<body ng-controller="myCtrl">
    <select id="shiftnumbers"
            ng-model="event.shiftnumber"
            ng-change="addShiftNumber(event.shiftnumber)"
            ng-options="timeslot.value as timeslot.name for timeslot in shiftnumbers"
            ng-init="event.shiftnumber = shiftnumbers[0].value"
            class="btn">
    </select>
    <div ng-repeat="shiftnumber in selectedShiftnumbers">
      <input type="text" name="test{{shiftnumber}}" ng-model="test[shiftnumber]" /> {{shiftnumber + 1}}
    </div>
</body>

SCRIPT代码 -

var myApp = angular.module("myApp", []);

myApp.controller("myCtrl", function($scope){

    $scope.shiftnumbers = [];
    for(var i=0; i< 23; i++) {
        $scope.shiftnumbers.push({name: i, value: i});
    }

    $scope.addShiftNumber = function(num){
      $scope.selectedShiftnumbers = [];
      for(var i=0; i< num; i++) {
        $scope.selectedShiftnumbers.push(i);
      }
    }
});

PLNKR - http://plnkr.co/edit/PL9sVAKn5UsZECPsOvnk?p=preview

1 个答案:

答案 0 :(得分:3)

因为您没有定义$scope.test[0]$scope.test[1](您使用ng-model="test[shiftnumber]",所以应该有$scope.test[shiftnumber])。

尝试

$scope.addShiftNumber = function(num){
  $scope.test = [];
  $scope.selectedShiftnumbers = [];
  for(var i=0; i< num; i++) {
    $scope.selectedShiftnumbers.push(i);
    $scope.test.push('');
  }
}

plunker