Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 332
Ole Spaarmann Avatar asked Jun 19 '15 21:06

Ole Spaarmann


2 Answers

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! :)

like image 188
Daniel Jamrozik Avatar answered Oct 16 '22 01:10

Daniel Jamrozik


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>
like image 45
Ajeet Lakhani Avatar answered Oct 16 '22 02:10

Ajeet Lakhani