我在ng-repeat
中使用了一系列对象。每个对象都有一个嵌套对象数组,其中包含一个字段。一个例子:
{
"_id": "55927dc3d2d258ac62fcdb36",
"title": "Some title",
"username": "test1",
"voted": [
{
"username": "bill"
},
{
"username": "ben"
},
{
"username": "sarah"
}
]
},
{
"_id": "55927dc3d2d258ac62fcdabc",
"title": "Another title",
"voted": [
{
"username": "someone"
}
]
},
{
"_id": "55927dc3d2d258ac62fcddef",
"title": "Something else",
"voted": []
}
对于每个对象,我想检查voted
数组中的一个嵌套对象是否具有完全匹配数组外部变量的值。如果找到匹配项,我想将新字段推送到相关对象(voted
数组之外),以便可以向用户显示“标记”。
I have an example 'working', but not as I want it to。我使用angular.forEach
迭代每个项目,然后迭代voted
,并检查voted.username
个字段是否与$scope.randomNameExample
匹配。如果找到匹配项,我会将新对象推送到$scope.items
:
$scope.randomNameExample = 'bill';
var items = [
{ ... },
{ ... },
{ ... },
{ ... }
];
$scope.items = items;
angular.forEach(items, function(item) {
angular.forEach(item.voted, function(voted) {
if(voted.username === $scope.randomNameExample) {
console.log("username is the same - push $scope!");
var matchingUsernamesObj = {matchingUsernames: true};
$scope.items.push(matchingUsernamesObj);
console.log(this);
}
}, $scope.items);
}, $scope.items);
模板:
<li ng-repeat="item in items">
<p>{{item.title}}</p>
<p>by {{item.username}}</p>
<!-- if item.voted[X].username matches randomNameExample, show this element -->
<p ng-show="item.matchingUsernames" class="its-happened">already voted.</p>
</li>
这样做 - “标志”显示在相关项目中,但项目对象的其余部分被完全覆盖。
为什么会这样?
如何确保在推送新对象时原始对象保持不变?
我可能想要推送一个新的字段而不是一个对象,但知道两者都很好。
此外,有没有更好的方法来实现纯角度的这种结果?我确信这种方法有一些很好的lodash方法,但我现在不想引入lodash。
答案 0 :(得分:1)
目前,只要找到匹配项,您就会在列表中添加没有任何标题或用户名的新项目。我不知道这是否有意,但您可能只想在matchingUsernames
上设置匹配的item
属性。
angular.forEach(items, function(item) {
angular.forEach(item.voted, function(voted) {
if(voted.username === $scope.randomNameExample) {
item.matchingUsernames = true;
}
}, $scope.items);
}, $scope.items);
以下是fiddle的更新版本。