Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-ng-repeat

Angular JS - Text box not getting updated after clearing


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


Solution

  • In your clear function do below code to clear value.

    this.user = { name: "" };