簡體   English   中英

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元素。 我只是不確定如何使用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演示

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);
    }

添加了額外功能,將在選擇圖像數量時執行。 選擇一個數字后,如果要減少該數字,則也可以減小數組大小。 為此,我補充了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM