里面ngIf绑定元素不更新绑定 [英] bound element inside ngIf does not update binding
问题描述
我已经写了angularjs指令。
在该指令的模板,我增加了一个ngIf指令,并在其中我显示绑定到我的指令的范围输入。
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>
我注意到,大量的试验和错误的ngIf指令引起,当输入文本更改为没有更新的模式之后。如果我把它改为ngShow一切正常。
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
推荐答案
这是怎么回事,因为ngIf创建一个新的子范围,所以如果你想绑定到同一范围内的其他投入,我们可以去下一层以$家长。检查 来了解更多关于继承的范围
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;
}
}
});
看看新的jsfiddle
这篇关于里面ngIf绑定元素不更新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!