MegaRacer MegaRacer - 1 month ago 14
AngularJS Question

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?

Answer

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