Ole Spaarmann
Ole Spaarmann

Reputation: 16749

How to get the value of a field with ng-change

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.

<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>

Upvotes: 14

Views: 49761

Answers (3)

Muhammad Hamza
Muhammad Hamza

Reputation: 11

 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>

Upvotes: 0

Ajeet Lakhani
Ajeet Lakhani

Reputation: 3848

You can make use of $event for getting value of current element. Something like this

<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>

Upvotes: 11

Daniel Jamrozik
Daniel Jamrozik

Reputation: 1238

ng-model

It'll store the value of an input, textarea, or select.

Your html should be like this:

<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

Hope that helps! :)

Upvotes: 12

Related Questions