ngIf 内的绑定元素不更新绑定

编程入门 行业动态 更新时间:2024-10-21 13:30:00
本文介绍了ngIf 内的绑定元素不更新绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我写了一个 angularjs 指令.在该指令的模板中,我添加了一个 ngIf 指令,并在其中显示了一个绑定到指令范围的输入.

我注意到,经过大量试验和错误后,ngIf 指令会导致模型在输入文本更改时无法更新.如果我将其更改为 ngShow,一切都会按预期进行.

我正在寻找这种差异的解释

我在这里创建了一个 jsfiddle

解决方案

这是因为 ngIf 创建了一个新的子作用域,所以如果你想绑定到与其他输入相同的作用域,我们可以用 $ 向下一级父母.查看此处以了解有关范围继承的更多信息

 angular.module('testApp', []).directive('testDir', function () {返回 {限制:'A',模板:'<input ng-model="foo"><input ng-model="foo">'+'<div ng-if="bool"><input ng-model="$parent.foo"></div>',链接:函数(范围,元素,属性){scope.foo = "bar";scope.bool = true;}}});

看看新的 jsfiddle

I have written a angularjs directive. in this directive's template I have added an ngIf directive and within it I display an input that is bound to my directive's scope.

<div ng-if="bool"><input ng-model="foo"></div>

I noticed, after a lot of trial and error that the ngIf directive cause the model to not get updated when the input text is changed. If I change it to ngShow everything works as expected.

I am looking for an explanation of this difference

I have created a jsfiddle here

解决方案

It's happening because ngIf creates a new child scope, so if you want to bind to the same scope as the other inputs, we can go one level down with $parent. Check here to understand more about scope inheritance

  angular.module('testApp', [])
  .directive('testDir', function () {
    return {
      restrict: 'A',
      template: '<input ng-model="foo"><input ng-model="foo">' +
         '<div ng-if="bool"><input ng-model="$parent.foo"></div>',
      link: function (scope, elem, attrs) {
        scope.foo = "bar";
        scope.bool = true;       
      }
    }
  });

Take a look to new jsfiddle

这篇关于ngIf 内的绑定元素不更新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 22:55:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1011323.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   素不   ngIf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!