【问题标题】:AngularJS : using ng-repeat and ng-model to populate an arrayAngularJS:使用 ng-repeat 和 ng-model 填充数组
【发布时间】:2015-06-04 10:30:54
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 检查更新的 HTML。您可以在选项中使用ng-opttions 而不是使用 ng-repeat
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 2014-06-18
    • 1970-01-01
    相关资源
    最近更新 更多