andrzej andrzej - 2 months ago 31
AngularJS Question

Angular ng-model ng-repeat clear all input

Why function

clear()
doesn't work in this example below ?

HTML:

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body>
<div class="wrapper" ng-app="app" ng-controller="AppController">
<div class="form-control" ng-repeat="n in [] | range:number">
<input type="text" ng-model="newVar" />
<span>{{newVar}}</span>
</div>
<!-- //form controll -->
<input type="range" ng-model="number" max="9" />
<label>Repeat input fields {{number}} times</label>
<button ng-click="clear()">clear</button>
</div>
</body>

</html>


Controller:

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

app.controller('AppController', function($scope) {
$scope.number = 5;
$scope.newVar = 0;
$scope.clear = function() {
$scope.newVar ='';
}
});//AppController

app.filter('range', function () {
return function (input, total) {
total = parseInt(total);
for (var i = 0; i < total; i++) {
input.push(i);
}
return input;
}; //filter range
});


here is my plnkr

Answer

ng-repeat creates a child scope for every 'repeat', so you can access the controller's scope by using $parent. In addition, you can use an array/object to store all values and not use just one variable for all the different lines in the view. You can do this using $index inside ng-repeat:

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div class="wrapper" ng-app="app" ng-controller="AppController">
    <div class="form-control" ng-repeat="n in [] | range:number">
      <input type="text" ng-model="$parent.newVar[$index]" />
      <span>{{newVar[$index]}}</span>
    </div>
    <!-- //form controll -->
    <input type="range" ng-model="number" max="9" />
    <label>Repeat input fields {{number}} times</label>
    <button ng-click="clear()">clear</button>
  </div>
</body>

</html>

This way clear() cleans all the values because it sets the whole object to an empty string.

That is why I would also change the clear function to something like this:

$scope.clear = function() {
        $scope.newVar = {};
}