简体   繁体   中英

get the value of input text in a directive (ANGULAR.JS)

http://jsfiddle.net/ccLwj3us/

Hi. this is my code. I need get the value of the input text, but I only can get the value, when the value on the input text ischanged. How can get the value of the input text without need change.(get initially the value of the input text)

I want to do something very generic, that I can reuse it in any controller. Have a certain number of fields and validate them, so I do not want to always get the value of the variable "number".

I want to reuse this directive on any controller. I will not always have the $ scope.numero variable. How can I get the value of the text field without typing scope.numero in the directive?

  var app = angular.module('app', []);

  app.controller('appCtrl', function ($scope) {
  $scope.numero=100500
  });

  app.directive('validate', function () {

      return {
          restrict: 'AE',
          require: 'ngModel', 

          link: function (scope, element, attrs, ngModel) {
            if (!ngModel){
              return;          
            }

            ngModel.$parsers.push(function(val){
              if ((val>10) && (val<20)){
                element.removeClass("wrong"); 
                element.addClass("correct"); 
              } else {
                element.removeClass("correct");
                element.addClass("wrong"); 
              }
              ngModel.$render();
            })


          }
      };
  });

The data you need is already inside the ngModel , so you can retrieve it with ngModel.$modelValue .

(In general, when using Angular it's best to get out of the habit of reading data from the DOM -- the DOM is a side effect representation of the scope data; there's no need for the directive to "read the data from the input field" because the input field was filled using data already in the directive in the first place!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM