Hari
Hari

Reputation: 98

How to clear input field in AngularJs?

When a user types anything in the input field and clicks the add button, the input is added into the array and gets displayed in the list.

However I am not able to clear the input field after pushing it into the array.

I am new to AngularJs, and would appreciate some help. Thanks in advance.

Here is my Code:

<div class="container">
<div ng-controller="mainController">
<input type="text" ng-model='name' placeholder="name">
<input type="text" ng-model='number' placeholder="number">
<button ng-click="addToList()">Add</button>
<ul ng-repeat="person in array_of_Names">
     <li>{{$index + 1}}.Name:{{person.name}},Phone:{{person.number}}</li>
</ul>
</div>
</div>

And my app.js:

 var myApp = angular.module('myApp', []);
 myApp.controller('mainController',['$scope',function($scope){
 $scope.array_of_Names = [];
 $scope.addToList = function(){
    var person = {
        name: $scope.name,
        number: $scope.number
    };
    $scope.array_of_Names.push(person);
 };

}]);

Upvotes: 3

Views: 11964

Answers (2)

Sahbaz
Sahbaz

Reputation: 1272

 $scope.addToList = function(){
    var person = {
        name: $scope.name,
        number: $scope.number
    };
    $scope.array_of_Names.push(person);
    $scope.name = null;
    $scope.number = null;
 };

That should do the job, just modify your addToList function to be like this.

Upvotes: 0

Paul Bursu
Paul Bursu

Reputation: 101

You can set

$scope.number = ""
$scope.name = ""

and that will change it in the HTML as well.

Your code will look like this:

 var myApp = angular.module('myApp', []);
 myApp.controller('mainController',['$scope',function($scope){
 $scope.array_of_Names = [];
 $scope.addToList = function(){
    var person = {
        name: $scope.name,
        number: $scope.number
    };
    $scope.name = "";
    $scope.number = "";
    $scope.array_of_Names.push(person);
 };

}]);

Upvotes: 4

Related Questions