BT101
BT101

Reputation: 3836

Populate inputs by number angularjs

I am trying to populate input by typing the number in input[number].

Why this doesn't work

// Code goes here

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

app.controller('MainCtrl', function($scope) {
    $scope.lengInput = {
        count: 0,
        values: [],
        fill: function(limit) {
            var sequence = [];
            for (var i = 0; i < limit; i++) {
                sequence.push(i);
            }
            return sequence;
        }
    };
});
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.js" data-semver="1.5.11"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <input ng-model="lengInput.count" type="number" min="1" max="20">
    <ul>
        <li ng-repeat="i in lengInput.fillSequence(lengInput.count)">
            <input ng-model="lengInput.values[i]" />
        </li>
    </ul>
  </body>

</html>

since this is working

JSFiddle Demo

Please find my mistake.

Upvotes: 0

Views: 50

Answers (1)

Naren Murali
Naren Murali

Reputation: 56755

Instead of attaching the function directly to the ng-repeat, you can use ng-init to intialize the $scope.lengInput.values and add an ng-change to the input field where $scope.lengInput.count is getting set, so that the function does not get run every time, instead it runs only when the value in the input box has changed!

// Code goes here

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

app.controller('MainCtrl', function($scope) {
  $scope.lengInput = {
    count: 0,
    values: [],
    fill: function(limit) {
      var sequence = [];
      for (var i = 0; i < limit; i++) {
        sequence.push(i);
      }
      $scope.lengInput.values = sequence;
    }
  };
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.js" data-semver="1.5.11"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="MainCtrl" ng-init="lengInput.fill(lengInput.count)">
  <p>Hello {{name}}!</p>
  <input ng-model="lengInput.count" type="number" min="1" max="20" ng-change=" lengInput.fill(lengInput.count)">
  <ul>
    <li ng-repeat="i in lengInput.values">
      <input ng-model="lengInput.values[i]" />
    </li>
  </ul>
</body>

</html>

Upvotes: 1

Related Questions