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

标签 javascript arrays angularjs angularjs-ng-repeat angularjs-ng-model

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

我的 Controller 的相关部分:

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

Controller

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

添加了额外的功能,该功能将在选择图像数量时执行。选择一个数字后,如果您想减少该数字,则数组大小也应该根据需要减小。为此我添加了。

关于javascript - AngularJS : using ng-repeat and ng-model to populate an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641453/

相关文章:

java - 声明一个数组 (type[] arrayName) 而不是 (type arrayName[])

javascript - 将文件从浏览器上传到 S3

javascript - 在 Javascript 中使用正则表达式标记字符串

Javascript onkeyup 有时会被触发两次

javascript - Mapbox如何通过鼠标滚动控制 map 缩放速度

python - 将一行拆分为多个单元格,并为每个基因保留第二个值的最大值

javascript - 事件代码在不同浏览器中的行为不同

c - 动态数组 C

angularjs - 为什么我收到错误...意外请求 : GET/internalapi/quotes

angularjs - 从 Angular 带模态返回数据