2014-08-27 120 views
-1

問題 -在AngularJS創建NG-模型動態名

ng-model沒有動態創建。我的輸入框正在動態創建,我正在嘗試創建ng-model動態,如test[1],test[2]等,但當我使用firebug時,我只能獲得 - 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> 

腳本代碼 -

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

回答

3

因爲你沒有定義$scope.test[0]$scope.test[1](你使用ng-model="test[shiftnumber]",所以t這裏應該是$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