gpt4 book ai didi

javascript - 确定集合并删除 Angular 中的一项特定项目

转载 作者:行者123 更新时间:2023-12-03 03:04:58 26 4
gpt4 key购买 nike

从这个例子开始:

<div ng-repeat="item in collectionA track by item.instanceid">
<input id="{{item.instanceid}}" style="display:none">
<input ng-model="item.name" type="text">
<button onclick="Remove({{item.instanceid}})">Remove</button>
</div>
<div ng-repeat="item in collectionB track by item.instanceid">
<input value="{{item.instanceid}}" style="display:none">
<input ng-model="item.name" type="text">
<button onclick="Remove({{item.instanceid}})">Remove</button>
</div>

<script>
function Remove(instanceid){
var container = $('#'+instanceid).closest('div');
var scopeItem = angular.element(container).scope();
....
}
</script>

这是我的用例的简化,但我需要保留这种代码结构。因此,从这一点开始,我想知道在Remove函数中是否可以从collectionA或collectionB中删除一个只知道其instanceid(根据定义是唯一标识符)的对象)。

最佳答案

与其将 Angular 与普通的 JS 做事方式混合在一起,为什么不充分利用 Angular 的强大功能呢?

具体来说,我指的是使用 ng-click而不是onclick :

<button ng-click="Remove($index, 'collectionA')">Remove</button>

然后在你的 Controller 中:

$scope.Remove = function(index, collection) {
$scope[collection].splice(index, 1);
};

使用$index from ng-repeat 消除了根据instanceid 搜索数组的需要。

编辑:OP声称他需要一种使用intanceid删除数组项的方法。 ,我将继续展示如何进行,尽管我不确定他如何确定要搜索的集合:

$scope.Remove = function(instanceid) {
for (var i = 0, len = $scope.collection.length; i < len; i++) {
if ($scope.collection[i].instanceid === instanceid) {
$scope.collection.splice(i, 1);
return;
}
}
};

关于javascript - 确定集合并删除 Angular 中的一项特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47212808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com