Search code examples
angularjsangular-ngmodelangular-controller

How can I place the default value in the input text box


I have the below code. I want to have the default value assigned to the script variables initially shown in the box. Later the value must change according to user's input in the text box.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title> Hello app </title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
    </head>
    <body>
    <div ng-app="testapp">
        <p> Enter your name: <input type="text" ng-model="name"></p>
        <p> Enter your age here: <input type="text" ng-model="age"> </p>
        <ol>
          <li> My Name is {{ name }} </li>
          <li>I am {{ age}} years old </li>
        </ol>

       <script>
       var app = angular.module("testapp",[]);
       app.controller=("test", function($scope){
       $scope.age = "20"
       $scope.name = "zigo"
       });
       </script>
   </div>
   </body>
   </html>

I want "20" and "zigo" to be initially shown in the text box. How can i change my code?


Solution

  • You are missing ng-controller in html and the controller should be,

     app.controller("test", function($scope){
    

    NOT

    app.controller=("test", function($scope){
    

    DEMO

      var app = angular.module("testapp",[]);
     app.controller("test", function($scope){
           $scope.age = "20"
           $scope.name = "zigo"
     });
     <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title> Hello app </title>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
        </head>
        <body>
        <div ng-app="testapp" ng-controller="test">
            <p> Enter your name: <input type="text" ng-model="name"></p>
            <p> Enter your age here: <input type="text" ng-model="age"> </p>
            <ol>
              <li> My Name is {{ name }} </li>
              <li>I am {{ age}} years old </li>
            </ol>
     
       </div>
       </body>
       </html>