简体   繁体   中英

How to push i times in an array of objects in angularjs

I have a data( $scope.users ) that I displays in the view. When the $scope.users length is less than 5 it should display 2 empty rows with null input boxes to make it 5 rows. The goal of the page is to display 5 rows even the other data is null.

I used $scope.users.push({}) to add. I also created a for loop but it only push a one row. It should add how many rows is needed.

What is wrong in my codes?

 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> 

If length is 3 then you loops condition will be i < 2 .

But you loop start from 1 and seek for i < 2 .

After first iteration i will be 2 but your condition seeking value less then 2

Convert this

i < 5 - $scope.users.length

to this

i <= 5 - $scope.users.length

Or start from 0 instead of 1

Like this

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

You can make use of while loops:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM