点击访问其他元素值

ng-click accessing other element values

本文关键字:元素 其他 访问      更新时间:2023-09-26

我试图访问输入时点击按钮的值:

控制器:

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>

但是'undefined'是在警报中出现的。这在角度上是如何实现的?

ng-model在期望的input

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

但是如果你像这样改变顺序

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

你不会得到myInput的值。在这种情况下,你会觉得很奇怪!顺便说一下如果你把按钮放在div栏上,可能就会出现这个问题