Open In App

How to set the input field value dynamically in AngularJS ?

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an input field and the task is to set the input field value dynamically with the help of AngularJS.

Approach: 

  • A value is being set to the input field despite the user enter something or not. 
  • ng-click event is used to call a function that sets the value to 'This is GeeksForGeeks' with the help of ng-model.

Example 1: In this example, the input field is read-only So the user can not modify it and the value is set dynamically.

HTML
<!DOCTYPE HTML>
<html>

<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>

    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.nameText = '';
            $scope.setVal = function () {
                $scope.nameText = "This is GeeksForGeeks";
            };
        });
    </script>
</head>

<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>


    <p>
        How to set the <input> field 
        value dynamically in AngularJS
    </p>

    <div ng-app="app">
        <div ng-controller="controller">
            Input field: <input type="text" 
                readonly name="mytext" 
                ng-model="nameText">
            <br><br>
            <input type="button" 
                ng-click="setVal()" 
                value="Set Dynamically">
            <br>
        </div>
    </div>
</body>

</html>

Output:

Example 2: In this example, user can modify the input field but the value entered by user can be set dynamically.

HTML
<!DOCTYPE HTML>
<html>

<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>

    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.nameText = '';
            $scope.setVal = function () {
                $scope.nameText = "This is GeeksForGeeks";
            };
        });
    </script>
</head>

<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>


    <p>
        How to set the <input> field 
        value dynamically in AngularJS
    </p>

    <div ng-app="app">
        <div ng-controller="controller">
            Input field: <input type="text" 
                name="mytext" ng-model="nameText">
            <br>
            <br>
            <input type="button" 
                ng-click="setVal()" 
                value="Set Dynamically">
            <br>
        </div>
    </div>
</body>

</html>

Output:


Next Article

Similar Reads