简体   繁体   English

获取指令中输入文本的值(ANGULAR.JS)

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

http://jsfiddle.net/ccLwj3us/ 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". 有一定数量的字段并对其进行验证,所以我不想总是获取变量“ number”的值。

I want to reuse this directive on any controller. 我想在任何控制器上重用此指令。 I will not always have the $ scope.numero variable. 我将不会总是拥有$ scope.numero变量。 How can I get the value of the text field without typing scope.numero in the directive? 如何在不在指令中键入scope.numero的情况下获取文本字段的值?

  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 . 您需要的数据已经在ngModel内部,因此您可以使用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!) (通常,使用Angular时,最好摆脱从DOM读取数据的习惯-DOM是作用域数据的副作用表示;无需使用指令“从输入字段读取数据”,因为输入字段首先是使用指令中已有的数据填充的!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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