0

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.