HalfWebDev
HalfWebDev

Reputation: 7668

Re-render NgRepeat based on user typed value input field

I have div which has some markup inside it. Basically some form fields which I want to save too on submission.

Outside this div, I have an input field where user can type an integer. Based on this integer, I would like to show or ng-repeat items.

Here's the sample code matching my problem. Kept a span inside of any form elements to focus on main issue of ng-repeat.

var app = angular.module('myapp',[]);
app.controller('ctrlParent',function($scope){
    $scope.myNumber = 3;

    $scope.getNumber = function(num) {
        return new Array(num);   
        $scope.$apply();
    }
    
    $scope.$watch('myNumber', function(newVal,OldVal){
    	$scope.myNumber = newVal;
      //alert(newVal);
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
    <div ng-controller="ctrlParent">
    <input type="text" ng-model="myNumber" ng-blur="getNumber(myNumber)"/>
        <ul>
            <li ng-repeat="i in getNumber(myNumber) track by $index">
              
              <span>{{$index+1}}</span>
            </li>
        </ul>
        
       
    </div>
</div>

here's what I tried :

  1. Watching the variables and assigning newValue of input to scope variable does not help.
  2. I tried using ng-blur to call the same function with updated value. Oh yes, ng-change was tried too.
  3. Used $scope.$apply() inside getNumber function out of desperation to manually update the changes.

How do I proceed with it ? Is there any way to update the ng-repeat?

Upvotes: 1

Views: 719

Answers (2)

ram1993
ram1993

Reputation: 971

It is not an issue of ng-repeat, you have used input of type text. Change it to number or use parseInt.

Upvotes: 2

whyyie
whyyie

Reputation: 792

You do not need to use ng-blur, $watch, $scope.$apply() for detecting the changes in your case.

You got this part wrong: <input type="text" ng-model="myNumber">, in which you should change the input to type number.
new Array() accept number and you pass text over it.

var app = angular.module('myapp', []);
 app.controller('ctrlParent', function($scope) {
   $scope.myNumber = 3;

   $scope.getNumber = function(num) {
     return new Array(num);
   }
 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="ctrlParent">
    <input type="number" ng-model="myNumber" />
    <ul>
      <li ng-repeat="i in getNumber(myNumber) track by $index">
        <span>{{$index+1}}</span>
      </li>
    </ul>
  </div>
</div>

Upvotes: 0

Related Questions