Javascript 如何使用 ng-change 获取字段的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30947808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the value of a field with ng-change
提问by Ole Spaarmann
I know how to react to user input in a textarea with ng-change in AngularJS. But how can I get the current input inside the Angular controller? I am missing something like $(this).value();
in jQuery.
我知道如何使用 AngularJS 中的 ng-change 对 textarea 中的用户输入做出反应。但是如何在 Angular 控制器中获取当前输入?我缺少类似$(this).value();
jQuery 的东西。
<script>
angular.module('changeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.evaluateChange = function() {
console.log("How do I get the current content of the field?");
};
}]);
</script>
<div ng-controller="ExampleController">
<textarea ng-change="evaluateChange()" id="ng-change-example1"></textarea>
</div>
回答by Daniel Jamrozik
ng-model
ng模型
It'll store the value of an input, textarea, or select.
它将存储输入、文本区域或选择的值。
Your html should be like this:
你的 html 应该是这样的:
<div ng-controller="ExampleController">
<textarea ng-model="myValue" ng-change="evaluateChange()" id="ng-change-example1"></textarea>
</div>
Then in your controller you can reference that with $scope.myValue
然后在您的控制器中,您可以使用 $scope.myValue
Hope that helps! :)
希望有帮助!:)
回答by Ajeet Lakhani
You can make use of $event for getting value of current element. Something like this
您可以使用 $event 来获取当前元素的值。像这样的东西
<script>
angular.module('changeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.evaluateChange = function(obj,$event) {
var currentElement = $event.target;
console.log(currentElement.value);//this will give you value of current element
};
}]);
</script>
<div ng-controller="ExampleController">
<textarea ng-change="evaluateChange(this)" id="ng-change-example1"></textarea>
</div>
回答by Muhammad Hamza
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.myFunc = function(vals) {
console.log(vals);
$("#result").html(vals);
};
}]);
body{
background:#ffc10721;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl" align="center">
<p>Write something in the Textarea</p>
<textarea ng-change="myFunc(myValue)" ng-model="myValue"></textarea>
<br>Result :<p id="result"></p>
</div>
</body>
</html>