AngularJS : 使用 ng-repeat 和 ng-model 填充数组

AngularJS : using ng-repeat and ng-model to populate an array

我正在尝试使用 ng-repeat 和 ng-model 来填充数组。数组中所需元素的数量来自 select 元素。

我控制器的相关部分:

app.controller('AddMsgCtrl', function($scope){
    $scope.range = function(n){
        var array = [];
        for(var i = 0 ; i < n ; i++)
            array.push(i);
        return array;
    };

    $scope.images = ['1.gif', '2.gif', '3.gif', '4.gif', 'any.gif'];

    $scope.msg = { 'images': [] }

和我的相关部分html:

Number of images:
<select class="browser-default" ng-model="numOfImages" ng-init="numOfImages=0">
    <option ng-repeat="number in range(6)" value="{{number}}">{{number}}</option>
</select>
<div>
    <div ng-repeat="n in range(numOfImages) track by $index">
        <select class="browser-default" ng-model= ???>
             <option ng-repeat="image in images" value="{{image}}">{{image}}</option>
        </select>
   </div>
</div>

现在用户可以 select 他们希望输入的图像数量,并且会显示相同数量的 select 元素。我只是不确定如何使用 ng-model 将所选元素添加到 $scope.msgs.images 数组。

编辑: 我比我想象的要近。这似乎工作正常:

<select class="browser-default" ng-model="msg.images[$index]">
     <option ng-repeat="image in images" value="{{image}}">{{image}}</option>
</select>

使用msg.images[$index] Plnkr Demo

HTML

    Number of images:
<select class="browser-default" ng-model="numOfImages" ng-init="numOfImages=0" ng-options="number for number in range(6)" ng-change="updateImages()">

</select>
<div>
    <div ng-repeat="n in range(numOfImages) track by $index">
        <select class="browser-default" ng-model="msg.images[$index]" ng-options="image for image in images">
        </select>
   </div>
</div>

Msg : {{msg}}

控制器

$scope.range = function(n){
        var array = [];
        for(var i = 0 ; i < n ; i++)
            array.push(i);
        return array;
    };

    $scope.images = ['1.gif', '2.gif', '3.gif', '4.gif', 'any.gif'];

    $scope.msg = { 'images': [] };

    $scope.updateImages = function() {
      // alert($scope.numOfImages);
      $scope.msg.images.splice($scope.numOfImages, $scope.msg.images.length);
    }

添加了额外的功能,它将在 select 图像数量上执行。一旦你 select 一个数字,如果你想减少这个数字,如果你愿意的话,数组的大小也应该减少。为此,我添加了。