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