gpt4 book ai didi

javascript - 如何在angularjs中的对象数组中推送i次

转载 作者:行者123 更新时间:2023-12-03 08:18:02 26 4
gpt4 key购买 nike

我有一个在 View 中显示的数据($scope.users)。当 $scope.users 长度小于 5 时,它应该显示 2 个带有空输入框的空行,使其成为 5 行。该页面的目标是显示 5 行,即使其他数据为空。

我使用$scope.users.push({})来添加。我还创建了一个 for 循环,但它只推送一行。它应该添加需要多少行。

我的代码有什么问题吗?

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function($scope) {

$scope.showRecords = function() {
$scope.users = [{
'id': 5,
'username': 'ady',
'role': 'Admin',
'img': 'Jellyfish.jpg',
}, {
'id': 7,
'username': 'tiu',
'role': 'Admin',
'img': 'Jellyfish.jpg',
}, {
'id': 4,
'username': 'ert',
'role': 'Admin',
'img': 'Jellyfish.jpg',
}];


if ($scope.users.length < 5) {

for (var i = 1; i < 5 - $scope.users.length; i++) {
$scope.users.push({});
}

}

}

$scope.submit = function(users) {
console.log(users);

}

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="mymodal">
<div ng-controller="MainCtrl" class="container">


<table class="table table-bordered">
<tr ng-repeat="row in users">
<!-- <td>{{row.id}}</td>
<td>{{row.username}}</td>
<td>{{row.role}}</td> -->
<td>
<input type="text" ng-model="row.id" name="id">
</td>
<td>
<input type="text" ng-model="row.username" name="username">
</td>
<td>
<input type="text" ng-model="row.role" name="role">
</td>

</tr>
</table>
<button ng-click="showRecords();">Show Record</button>

<button ng-click="submit(users);">Submit new record</button>

最佳答案

如果长度是3那么你的循环条件将是 i < 2 .

但是你循环从 1 开始并寻找i < 2 .

第一次迭代后i将是2但您的条件寻求值(value)小于 2

转换此

i < 5 - $scope.users.length

到此

i <= 5 - $scope.users.length

或者从0开始而不是1

像这样

for (var i = 0; i < 5 - $scope.users.length; i++)

关于javascript - 如何在angularjs中的对象数组中推送i次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33850843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com