我有 2 组连续加载的数据。
第一个数据将通过 id 定义要重复和跟踪的项目。
items:
[{"id":21, "name":"john doe"},{"id":15, "name":"john doe"},{"id":13, "name":"john doe"}]
我加载的下一组数据将确定项目的一些状态,由“id”匹配。
[{"idToMatch":15, "status":1},{"idToMatch":13, "status":1}]
我可以通过这样做来重复 dom 项
<div ng-repeat="item in items trackby item.id">
{{item.name}}
</div>
我想做的是将一个类添加到第二个列表中与“idToMatch”匹配到第一个集合的“id”的项目。
最佳答案
我会做什么:
在你的 Controller 中:
//just for example
$scope.matches = [{"idToMatch":15, "status":1},{"idToMatch":13, "status":1}];
$scope.doesItemMatch = function(item) {
for(var i in $scope.matches) {
var match = $scope.matches[i];
if(item.id === match.idToMatch)
return true;
}
return false;
}
然后在你的 html 中:
<div ng-repeat="item in items trackby item.id" ng-class="{yourClass: doesItemMatch(item)}">
{{item.name}}
</div>
[编辑]:这是一个运行示例
angular.module('test', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.items = [{
"id": 21,
"name": "john doe"
}, {
"id": 15,
"name": "john doe"
}, {
"id": 13,
"name": "john doe"
}];
$scope.matches = [{
"idToMatch": 15,
"status": 1
}, {
"idToMatch": 13,
"status": 1
}];
$scope.doesItemMatch = function(item) {
for (var i in $scope.matches) {
var match = $scope.matches[i];
if (item.id === match.idToMatch)
return true;
}
return false;
}
}
]);
.test-class {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="test">
<div ng-controller="ExampleController">
<div ng-repeat="item in items" ng-class="{'test-class': doesItemMatch(item)}">
{{item.name}}
</div>
</div>
</body>
关于javascript - Angular : ng-repeat. 我如何根据值定位特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148681/