4
$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?

4 Answers 4

13

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

2

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

}

Comments

1

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.