How to retrieve the value from textbox using AngularJs?

34,938

Solution 1

Assign ng-model to it so that variable will be available inside scope of controller.

Markup

<input type='text' ng-model="myVar"/>
<button type="button" ng-click='add(myVar)'></button>

Solution 2

Bind the text field using ng-model

Example:

$scope.items = [];
$scope.newItem = {
  title: ''
}

$scope.add = function(item) {
  $scope.items.push(item);
  $scope.newItem = { title: '' }; // set newItem to a new object to lose the reference
}

<input type='text' ng-model='newItem.title'><button ng-click='add(newItem)'>Add</button>
<ul>
  <li ng-repeat='item in items'>{{ item.title }}</li>
</ul>

Solution 3

To take your data from textbox, you should use ng-model attribute on the HTML element. On the button element you can use ng-click with a parameter which is your ng-model

Example: Your HTML:

<input type='text' ng-model="YourTextData"/>
<button type="button" ng-click='add(YourTextData)'></button>

Your Js:

$scope.add=function(YourTextData){

       //Put a debugger in here then check the argument

}

Solution 4

Use ng-model in your textbox to bind them to your scope variables

<input type="text" ng-model="value1">
<input type="text" ng-model="value2">

Then declare the variables inside your controller and use them in your function

$scope.value1 = 0;
$scope.value2 = 0;
$scope.add=function()
    {
       // Example
       console.log($scope.value1 + $scope.value2);
    }
Share:
34,938
Naga Bhavani
Author by

Naga Bhavani

Updated on January 27, 2020

Comments

  • Naga Bhavani
    Naga Bhavani over 4 years
    $scope.add=function()
                    {
                        //How to retrieve the value of textbox
                    }
    
    <input type='text'><button ng-click='add()'></button>
    

    When I click on the button, how can I retrieve the textbox value in the controller and add that value to the table dynamically?