【发布时间】:2023-04-01 16:20:01
【问题描述】:
我很难理解为什么如果我在 ng-repeat 中使用按索引跟踪,在从数组中删除一个项目后,我会在指令范围内得到“错误”的值。
正如您在下面的 plunker 中看到的,如果我删除索引跟踪的数组中的第一个项目,指令范围内的值将不是初始值。
我期望在删除后有: 2 - b 3 - c
但我明白了 2 - 一个 3 - b
如果我不使用按索引跟踪,我会得到正确的值。
这是脚本
nsTests.controller('nsTestCtrl', ['$rootScope', '$scope', '$filter', '$timeout',
function ($rootScope, $scope, $filter, $timeout) {
$scope.data = [
{
id: 1,
name: 'a'
},
{
id: 2,
name: 'b'
},
{
id: 3,
name: 'c'
},
];
$scope.data2 = [
{
id: 1,
name: 'a'
},
{
id: 2,
name: 'b'
},
{
id: 3,
name: 'c'
},
];
$scope.removeByIndex = function (index) {
$scope.data.splice(index, 1);
}
$scope.removeByItem = function (item) {
var index = $scope.data2.indexOf(item);
if (index !== -1) {
$scope.data2.splice(index, 1);
}
}
}
]);
nsTests.directive('test', function ($compile) {
return {
restrict: 'E',
template: '{{value}}',
scope: {
data: '='
},
controller: function ($scope) {
$scope.value = $scope.data.name;
}
};
});
这里是plunker 的问题
【问题讨论】:
-
这似乎是您的指令的一些错误行为。如果你记录你的实际数据数组,你会看到数组实际上只剩下'b'和'c',但你的指令一直显示'a'
-
我相信 angular 并没有通过脏检查正确检测到指令的值变化,所以你必须进行其他检查
标签: angularjs angularjs-ng-repeat angular-directive