我知道如何使用AngularJS中的ng-change对textarea中的用户输入作出反应。但是如何在Angular控制器中获取当前输入?我在jQuery中遗漏了$(this).value();
之类的内容。
<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>
答案 0 :(得分:12)
您可以使用$ 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>
答案 1 :(得分:11)
NG-模型
它会存储输入,文本区域或选择的值。
你的HTML应该是这样的:
<div ng-controller="ExampleController">
<textarea ng-model="myValue" ng-change="evaluateChange()" id="ng-change-example1"></textarea>
</div>
然后在您的控制器中,您可以使用$scope.myValue
希望有所帮助! :)
答案 2 :(得分:-1)
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.myFunc = function(vals) {
console.log(vals);
$("#result").html(vals);
};
}]);
&#13;
body{
background:#ffc10721;
}
&#13;
<!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>
&#13;