简体   繁体   中英

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?

With ng-model on the desired input

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM