gpt4 book ai didi

angularjs - 以 Angular 管理相关对象的最佳方法?

转载 作者:行者123 更新时间:2023-12-01 02:25:33 25 4
gpt4 key购买 nike

假设我有两个 json 对象,一个用户和一个帐户,例如:

users = [
{id: 1, account_id: 1},
{id: 2, account_id: 2},
{id: 3, account_id: 1}
]

accounts = [
{id: 1, name: "administrator"},
{id: 2, name: "moderator"}
]

所以我必须遍历所有用户数组,并为每个用户获取帐户信息。管理这些关系以在标记中访问它们的最佳方法是什么?我找到了以下解决方案:

方法 1:只对一个元素进行重复,这样只需过滤元素并使其在标记的那部分可用
<div ng-repeat="user in users">
<div ng-repeat="account in getAccountFromId(user.account_id)">
<!-- now account is available in all this scope to access user.account.name -->
</div>
</div>

方式二:改变后台返回信息的方式,每个用户带一个json,每个json都带账号信息返回。但这会在每个 json 对象中重复很多信息。这也意味着由于 Angular 而改变后端。
<div ng-repeat="user in users">
<!-- with this approach I can access here user.account.name -->
</div>

有人能告诉我这些方法是否正确吗?有没有更好的方法来管理 angular 中的对象关系?

非常感谢。

最佳答案

如果您真的不喜欢更改来自服务器的数据形状的想法,另一种选择是将用户映射到 javascript 中的帐户。

app.controller("MyController", function($scope) {

// Pretend that 'users' and 'accounts' here came from an xhr request
var users = [
{id: 1, account_id: 1},
{id: 2, account_id: 2},
{id: 3, account_id: 1}
]

var accounts = [
{id: 1, name: "administrator"},
{id: 2, name: "moderator"}
]

// Map accounts to users
for(var i=0; i<users.length; i++) {
for(var j=0; j<accounts.length; j++) {
if (accounts[j].id === users[i].account_id) {
users[i].account = accounts[j];
}
}
}


});

关于angularjs - 以 Angular 管理相关对象的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16737895/

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