gpt4 book ai didi

javascript - 使用 Angular 语法删除数组中的对象

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

我正在尝试使用 Angular 通过界面管理标签列表。

我的范围内有一个服务器拉取的标签列表。

app.js

$scope.Tags = [{id:1, name:'tag1', desc:'desc1'}, {id:2, name:'tag2', desc:'desc2'}, {id:3, name:'tag3', desc:'desc1'}, ...];

我使用这段 html 代码显示列表:

tags.html

<ul>
<li ng-repeat="T in Tags">{{ T.name }}</li>
</ul>

当我点击<li>时我想要 Angular 元素删除关联的 Tag 对象。然后我按如下方式增强我的代码:

tags.html

<ul>
<li
ng-repeat="T in Tags"
ng-click="removeTag($event);"
>{{ T.name }}</li>
</ul>

app.js

$scope.removeTag = function (event) {

// the following code is just used to remove the Tag from the list
// using underscore.js

$scope.Tags = _($scope.Tags).filter(function (t) {
return t.name !== event.srcElement.innerHTML
});
}

这是可行的,但我希望有一种更简单的方法来执行相同的任务。而且我对 Angular 的经验仍然有限。

类似的东西会很棒:

<ul>
<li ng-repeat="T in Tags" ng-click="Tags - T">{{ T.name }}</li>
<!-- this is more like a dream tho -->
</ul>

最佳答案

尝试根据数组中的索引($index)拼接数组,如下所示:

<ul>
<li ng-repeat="T in Tags" ng-click="Tags.splice($index, 1)">{{T.name}}</li>
</ul>

关于javascript - 使用 Angular 语法删除数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29373975/

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