Lyndon Lyndon - 3 months ago 16
Javascript Question

ng-click accessing other element values

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?

Answer

With ng-model on the desired input

<input type="text" id="inputText" ng-model="myInput">
<button type="button" ng-click="test(myInput)">Test</button>