加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何将自定义输入指令及其父表单重置为$pristine

发布时间:2020-12-17 10:22:19 所属栏目:安全 来源:网络整理
导读:我已经实现了一个自定义输入指令 – 具有重置功能的计数器.该指令要求:“ngModel”. 我正在使用$setPristine()重置指令的ngModel的原始状态.与$setDirty()不同,$setPristine()不会触及父窗体的$pristine状态. 问:如何“通知”父表单此指令不再“脏”,以便
我已经实现了一个自定义输入指令 – 具有重置功能的计数器.该指令要求:“ngModel”.

我正在使用$setPristine()重置指令的ngModel的原始状态.与$setDirty()不同,$setPristine()不会触及父窗体的$pristine状态.

问:如何“通知”父表单此指令不再“脏”,以便父表单可以重置其$pristine状态?

请记住,只是调用表单.$setPristine()是不够的,因为表单中可能有其他“脏”控件,我的指令不会(也不应该)知道.

这是指令的链接功能:

link: function(scope,element,attrs,ngModel){

  var original;

  ngModel.$render = function(){
    original = scope.counter = ngModel.$viewValue;
  };

  scope.up = function(){
    ngModel.$setViewValue(++scope.counter);
  };

  scope.reset = function(){
    scope.counter = original;
    ngModel.$setViewValue(scope.counter);
    ngModel.$setPristine(); // this sets $pristine on the directive,but not the form
  };
}

以下是它的使用方法:

<div ng-form="form">
  <counter ng-model="count"></counter>
</div>

plunker

从Angular 1.3.x开始,没有内置的解决方案.

form.$setPristine()在其所有子控件上设置pristine. (link to code)

ngModel.$setPristine()只设置$pristine(link to code)

解决此问题的一种方法是创建一个与表单指令和劫持形式一起存在的指令.$setDirty用于跟踪脏控件计数.这可能最好在预链接阶段完成(即在子控件开始注册之前).

app.directive("pristinableForm",function() {
  return {
    restrict: "A",require: ["pristinableForm","form"],link: function(scope,ctrls) {
      var me = ctrls[0],form = ctrls[1];
      me.form = form;
      me.dirtyCounter = 0;
      var formSetDirtyFn = form.$setDirty;
      form.$setDirty = function() {
        me.dirtyCounter++;
        formSetDirtyFn();
      };
    },controller: function() {
      this.$notifyPristine = function() {
        if (this.dirtyCounter === 0) return;
        if (this.dirtyCounter === 1) {
          this.dirtyCounter = 0;
          if (this.form) this.form.$setPristine();
        } else {
          this.dirtyCounter--;
        }
      };
    }
  };
});

然后,自定义输入指令需要:[“ngModel”,“^ pristinableForm”]并在其reset函数中调用pristinableForm.$notifyPristine():

scope.reset = function(){
  if (ngModel.$dirty){
    scope.counter = original;
    ngModel.$setViewValue(scope.counter);
    ngModel.$setPristine();
    pristinableForm.$notifyPristine();
  }
};

用法是:

<div ng-form="form" pristinable-form>
  <counter ng-model="count1"></counter>
  <counter ng-model="count2"></counter>
  <input ng-model="foo" name="anotherControl">
</div>

plunker

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读