How do I get HTML form input value in AngularJs controller?

How do I get HTML form input value in AngularJs controller?
----------------------------------------------

In AngularJS, you can get the value of an HTML form input in a controller using two-way data binding or by accessing the form element's properties. Here are two approaches:

1. Two-way data binding:
   - In your HTML template, bind the input field using ng-model to a variable in the controller. For example:

<input type="text" ng-model="myInput">

   - In your AngularJS controller, you can access the value of the input field through the associated variable (myInput in this example). For example:

app.controller('MyController', function($scope) {
       $scope.myInput = ''; // Initialize the variable

       $scope.submitForm = function() {
         console.log($scope.myInput); // Access the input value
       };
     });

   - You can access the input value anytime in the controller using $scope.myInput

2. Accessing form element properties:
   - In your HTML template, add an id to the input field to give it a unique identifier. For example:

<input type="text" id="myInput">

   - In your AngularJS controller, you can access the input element using the angular.element function and retrieve its value. For example:

app.controller('MyController', function($scope) {
       $scope.submitForm = function() {
         var inputValue = angular.element(document.querySelector('#myInput')).val();
         console.log(inputValue); // Access the input value
       };
     });

   - In this approach, you access the input value using angular.element and the unique identifier (id) of the input field. The val() function retrieves the current value of the input field.

Both approaches allow you to retrieve the value of an HTML form input in an AngularJS controller. Choose the approach that best fits your specific use case and coding style.

Categories: AngularJS Tags: #AngularJs,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.