我对指令、范围和数组有疑问。我读到的是,如果我编写一个将范围设置为 true 的指令,我会得到一个与父范围分开的新范围。在这里,您可以在我的示例中看到我的两个指令。我的每个阵列一个。
kdApp.directive('kdinsurancesituationamount', function kdinsurancesituationamount() {
return {
restrict: 'E',
scope: true,
template: "<span>Name </span> " +
"<input value='{{name1}}' ng-model='name1'>" +
"<div ng-repeat='isa in insuranceSituationAmountList1'>" +
"<span>Amount {{$index}} </span> " +
"<input value='{{isa}}' ng-model='isa'>" +
" <br /></div>"
};
});
kdApp.directive('kdinsurancesituationamount2', function kdinsurancesituationamount2() {
return {
restrict: 'E',
scope: true,
template: "<span>Name </span> " +
"<input type='text' maxlength='9' value='{{name2}}' ng-model='name2'>" +
"<div ng-repeat='isa in insuranceSituationAmountList2'>" +
"<span>Index {{$index}} </span> " +
"<input type='text' maxlength='9' value='{{isa.amount}}' ng-model='isa.amount'>" +
" <br /></div>"
};
});
当我有像 $scope.name1 = "John"这样的变量时它工作正常但是当我有数组时我不明白它是如何工作的。在这里查看我的 Controller 。我有两个不同的示例,insuranceSituationAmountList1 和 insuranceSituationAmountList2。他们的工作方式不同。使用 ng-repeat 我在输入标签中写出数组,每个输入标签也有一个 ng-model 属性。
kdApp.controller('InsuranceSituationAmountController', function ($scope) {
$scope.insuranceSituationAmountList1 = ["1000", "2000", "3000"];
$scope.insuranceSituationAmountList2 = [{
amount: "4000"
}, {
amount: "5000"
}, {
amount: "6000"
}];
$scope.name1 = "John";
$scope.name2 = "John";
});
数组 insuranceSituationAmountList1 永远不会更新父范围,即使我在指令中将范围设置为 false。但是对于字段 name1,它可以按我的意愿工作。当范围为 false 时,字段名称 1 更新父范围,而当范围设置为 true 时,则不会。
数组 insuranceSituationAmountList2 将始终更新父范围,即使我在指令中将范围设置为 true 也是如此。但是对于字段 name2,它可以按我的意愿工作。 .当范围为 false 时,字段名称 2 更新父范围,而当范围设置为 true 时,则不会。
我有一个 jsfiddle,您可以在其中查看它的工作原理 http://jsfiddle.net/uhlrog/Lzcqeruw/66/因此,如果您有时间测试它,请先使用 scope: true 并更改为 scope:false 并更改输入框中的内容。
我想这是我不理解的基本原理,但有人可以为我解释为什么我的数组不能正常工作。
(如您所见,我的第一个语言不是英语 ;-))
最佳答案
好的..
首先你需要了解这个基本原理:
当“获取”范围值时,angular 将在层次结构中向上导航,直到找到它。 但是,当“设置”属性时,它只会将其放置在当前范围内。 (这是基于 javascript 继承的工作方式而不是 Angular 错误,所以不要责怪他们。)
所以.. 'getting' {{ name }} 例如将向上导航,直到它找到一个带有 name 的 $scope 并显示它。但是 'setting' {{ name = 'Changed' }} 不会在该范围内设置值。它会在第一个可用范围内设置它。
但是.. 'getting' {{ object.name }} 将向上导航范围,直到找到一个名为 object 的对象,然后显示它的名称属性,而 'setting' {{ object.name = 'Changed' }} 将首先需要“获取”“对象”(通过向上导航范围的层次结构)然后设置它的属性。哪个 $scope "object"打开时会更新。
现在如果你理解了这一点,它可能有助于解释发生了什么,这就是为什么 ng-repeat 在指令的第二个版本中更新正确的值。
现在,在第一个指令中,我明白了为什么当您将范围设置为 false 时相反的情况令人困惑。这是因为现在 ng-model="name1"与其父级在同一范围内并直接更新(没有 $scope 层次结构)但是也要记住 ng-repeat 确实创建了一个范围!。因此,由于数组值不包含在对象中,因此仅在单个 ng-repeat 范围内更新。
使用此 css 查看作用域:
.ng-scope {
border: 1px red solid;
}
我知道我可能没有很好地解释这一点(特别是如果英语不是你的第一语言,正如你提到的那样)但希望更新的 fiddle 会有所帮助..
Highlighting the problem和 Fixing the problem
这有助于记住,如果您使用不带“.”的 ng-model (点)然后该值将仅在它最近的范围内更新。
更新: This article如果您从我的尝试中不理解,可以帮助用图表突出显示此问题
关于javascript - 指令范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25746881/