1

I'm trying to access the value of an input when clicking on a button:

Controller:

app.controller('MainCtrl', function($scope) {
  $scope.test = function(val) {
    alert(val);
  }
});

HTML:

<body ng-controller="MainCtrl">
    <input type="text" id="inputText">
    <button type="button" ng-click="test(document.getElementById('inputText').value)">Test</button>
</body>

But 'undefined' is what comes up in the alert. How is this achieved in angular?

2 Answers 2

5

With ng-model on the desired input

<input type="text" id="inputText" ng-model="myInput">
<button type="button" ng-click="test(myInput)">Test</button>
Sign up to request clarification or add additional context in comments.

Comments

0

But if you switch the order like that

<button type="button" ng-click="test(myInput)">Test<//button>

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

you won't get the value of myInput. In this case you see it weird! by the way if you put your button in the div bar, maybe you will get this issue

1 Comment

Olla ! I get the solution. Put in your controller ... angular.element(document.getElementById('inputText')); ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.