簡體   English   中英

如何在angularjs中的對象數組中推送i次

[英]How to push i times in an array of objects in angularjs

我有一個數據( $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> 

如果length為3則循環條件為i < 2

但是您從1開始循環並尋找i < 2

第一次迭代后, i將為2但您的條件尋求的值小於2

轉換這個

i < 5 - $scope.users.length

對此

i <= 5 - $scope.users.length

或者從0開始而不是1

像這樣

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

您可以使用while循環:

    while($scope.users.length < 5) {
            $scope.users.push({});
    }

暫無
暫無

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

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