更改`ng-required`调用`ng-change`

时间:2016-11-24 08:53:00

标签: javascript angularjs forms

我在使用AngularJS 1.5.8的应用程序中有一个奇怪的行为:

  

plunker(https://plnkr.co/edit/zaHVJeK8hdxk2gaOL9Pf?p=preview)和视频(http://recordit.co/eszvfdfC9S

  • 第1步。在开始更改ng-required时,不会调用ng-change函数
  • 第2步。input进行更改并删除后input为空)ng-required致电ng-change函数

预期行为?

  • 第2步。input中进行更改并删除它们(input为空)ng-required不应调用ng-change函数。就像它在开始时一样,当输入有一些价值时

如果有错误,请告诉我。如果没有,那么为什么更改ng-required不会总是或甚至根本不更改ng-change

找到答案----------------------------------------- -------------------------------------------------- ------------

  

NgModelController有两个属性:$ viewValue(由...输入的值)   user)和$ modelValue(绑定到模型的值)。当值   由用户输入验证失败,NgModelController设置模型   未定义。

     

在AngularJS 1.3中,他们添加了ng-model-options指令。它可以让你   配置模型更新的方式/时间。你可以使用   allowInvalid选项可防止将模型设置为undefined:

ng-model-options="{allowInvalid: true}"

4 个答案:

答案 0 :(得分:6)

你应该添加

        ng-model-options="{allowInvalid: true}"

所以最后的结果将是

<input type="text" 
    ng-change="$ctrl.onChange()" 
    ng-required="$ctrl.isRequired"
    ng-model-options="{allowInvalid: true}"
    ng-model="$ctrl.val"
    />

答案 1 :(得分:2)

发生这种情况是因为当required需要设置为false时,ng-required正在将附加的模态值从空白处更改为未定义,因为此模式更改后会触发此更改。

检查plunker我有console.log输入的值,你可以清楚地看到模态的变化。

angular.
  module('myApp', []).
  component('greetUser', {
    templateUrl: 'tmpl.html',
    controller: function GreetUserController() {
      this.output='';
      this.isRequired = false; 

       console.log(this.val);

      this.onChange = function() {

        console.log(this.val);
        this.output+='Changed\n';
      }
    }
  });

plunker:https://plnkr.co/edit/6IeIjIDahcmBIU4KSASJ?p=preview

现在出现的问题是,为什么不加载/第一次更改事件没有启动,因为我们使用的是此对象而不是$ scope。

下面  'this' vs $scope in AngularJS controllers

是一个非常好的例子,它解释了为什么在我们手动输入输入中的值至少一次更改事件未启动之前。

简而言之,这种情况正在发生,因为ng-change / ng-model适用于范围变量。在输入元素中手动输入值后,模型绑定将与范围一起发生,并且ng-change事件开始启动。

答案 2 :(得分:0)

我认为你误解了。

ng-requiredng-change是不同的事情。做不同的目的,而不是互相打电话。

ng-change正在调用您的函数,无论它是否为空。对于输入中发生的变化,它会自行调用您的方法。

ng-required只是检查值是否为空,如果为空,则将其标记为无效。

为了得到你想要的东西,你必须检查onChange函数内的有效性。

this.onChange = function() {

    if( !$scope.$ctrl.form.$valid ) return;

    this.output+='Changed\n';
}

答案 3 :(得分:0)

我认为这就是原因。在这样的ng-change中发出警告。

this.onChange = function() {
        alert(this.val);
        this.output+='Changed\n';
      }

完成后清空框时,两个值之间的值会发生变化:

undefined  when is required 
''         when is not required 

因此,通过更改收音机框,您可以调用ng-change, 一开始你有

但是,当您尚未开始输入文本框时,单选框不会更改输入值,因为ng-change用于输入。一开始我们有undefined --> undefined所以没有任何改变。然后当你清空输入时,你有'' ---> undefined

实际上,如果你把它放在你的控制器中,你也可以在开始时调用ng-change。

this.val ='';

因此,如果用这个替换你的控制器,你会看到即使在开始时也会调用ng-change。

angular.
  module('myApp', []).
  component('greetUser', {
    templateUrl: 'tmpl.html',
    controller: function GreetUserController() {
      this.output='';
      this.isRequired = false; 
      this.val ='';
      this.onChange = function() {
        this.output+='Changed\n';
      }
    }
  });