gpt4 book ai didi

javascript - 在 Angular 中设置为 'active' 的对象数组

转载 作者:行者123 更新时间:2023-11-27 22:53:40 26 4
gpt4 key购买 nike

我有一个使用 ng-repeat 的项目列表

对象

var items = [{"name": "item1"},
{"name": "item2"}...
];

HTML

<div ng-repeat="item in items" ng-click="addItemToCollection(item)">
{{item.stuff}}
</div>

addItemToCollection 只是获取选择的一个并将其添加或拼接到不同的数组中,并应用一些逻辑来允许或拒绝它,所以我最终会得到类似的结果:

var selectedItems = [{"name": "item15"},
{"name": "item26"}...
];

如何将这个新数组绑定(bind)到原始数​​组上的 active 类,即如果单击 item3item5 ,设置两者都属于“活跃”类别?

即:

{{item1.stuff}}
{{item2.stuff}}
{{item3.stuff}} // (has class active based on 2nd array)
{{item4.stuff}}
{{item5.stuff}} // (has class active based on 2nd array)

地点:

selectedItems = [{"name": "item3"},
{"name": "item5"}...
];

在我的 ng-repeat 声明上设置 ng-class 以反射(reflect)这一点的最佳方法是什么?

最佳答案

我认为为 selectedItems 数组中的每个添加项添加一个类的最简单方法是用户使用以下代码:

<!-- toggle class with active field -->
<li class="list-group-item"
ng-repeat="item in items"
ng-class="{'active': active}"
ng-click="active = toggleSelect(item)"> <!-- set active field on select -->
{{ item }}
</li>

如您所见,我使用了 toggleSelect 函数,该函数根据切换状态(添加或删除项目)返回 bool。实现:

$rootScope.toggleSelect = function(item) {
var itemIndex = false;

//find item index if existing in selectedItems array
for(var i = 0; i < $rootScope.selectedItems.length; i++) {
if($rootScope.selectedItems[i].name === item.name) {
itemIndex = i;
}
}

//Add to array if not exists
if(itemIndex === false) {
$rootScope.selectedItems.push(item);
}
//Remove if item exists
else {
$rootScope.selectedItems.splice(itemIndex, 1);
}

//Return toggle status (item addition or removal)
return (itemIndex === false);
};

JS Bin example

关于javascript - 在 Angular 中设置为 'active' 的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37820771/

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