Reputation: 897
I am a beginner in Angular JS. While creating a sample application I have encountered the below problem of a text box not getting set once the value in its cleared using JavaScript.Below is my code:-
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function () {
this.showName = function () {
this.user = { name: "John" };
}
this.clear = function () {
document.getElementById("name").value = "";
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl as ctrl" class="container">
<input type="button" ng-click="ctrl.showName()" value="Show Name"/>
<input type="text" id="name" ng-model="ctrl.user.name" />
<input type="button" value="Clear" ng-click="ctrl.clear()" />
</div>
</body>
Her the first time I click on the Show name button I am getting the name in the text box.But if I clear the text box by clicking the Clear button and then click on the show button again the name is not getting filled in the text box. Can anyone please tell me why this is happening and anyways to fix this?
Here is my code in plunkr - http://plnkr.co/edit/MXlH2o?p=preview
Upvotes: 0
Views: 820
Reputation: 6459
change clear function to this code
this.clear = function () {
this.user.name="";
}
Upvotes: 1
Reputation: 8632
you don't need a clear() method in the controller, just take advantage of the double binding in angular, set the username to an empty string when you click on the button and the view will be updated consequently.
<input type="button" value="Clear" ng-click="ctrl.user.name = ''" />
Upvotes: 1
Reputation: 2897
Clear the name like this,
this.clear = function () {
this.user.name = "";
}
Upvotes: 1
Reputation: 1449
In your clear function do below code to clear value.
this.user = { name: "" };
Upvotes: 2