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

后端 未结 3 2077
遇见更好的自我
遇见更好的自我 2021-01-04 09:49

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 <

相关标签:
3条回答
  • 2021-01-04 10:12

     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>

    0 讨论(0)
  • 2021-01-04 10:24

    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>
    
    0 讨论(0)
  • 2021-01-04 10:31

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

    0 讨论(0)
提交回复
热议问题