问题描述
我写了一个 angularjs 指令.在该指令的模板中,我添加了一个 ngIf 指令,并在其中显示了一个绑定到指令范围的输入.
我注意到,经过大量试验和错误后,ngIf 指令会导致模型在输入文本更改时无法更新.如果我将其更改为 ngShow,一切都会按预期进行.
我正在寻找这种差异的解释
这是因为 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 内的绑定元素不更新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!