angularjs - Comparing two object arrays in angular ng-repeat
问题描述
I'm trying to compare two object arrays and check a checkbox for those that have the same object. below are the object array
objArray1 = [
{b: "AAA", c: 555, d:"RRR", e:"YYY"},
{b: "WWW", c: 985, d:"DDD", e:234},
{b: 675, c: 555, d:"RRU", e:"SSS"},
{b: "TTT", c: 905, d:"PPP", e:"GGG"}
]
objArray2 = [
{b: "AAA", c: 555, d:"RRR", e:"YYY"},
{b: "TTT", c: 905, d:PPP", e:"GGG"}
]
I tried using angular.equals but it's not working. Is there a way to do this in the view?
<tr ng-repeat="objs in objArray1 ">
<td>{{objs}}</td>
<td>
<input type="checkbox" id="{{$index}}"
ng-checked="angular.equals(objArray1,objArray2)" />
</td>
</tr>
Any solution
解决方案
创建一个辅助函数以在视图中使用,该函数将检查给定对象是否在第二个数组中。
var app = angular.module('app', []);
app.controller('ctrl', function() {
var $ctrl = this;
$ctrl.objArray1 = [
{b: "AAA", c: 555, d:"RRR", e:"YYY"},
{b: "WWW", c: 985, d:"DDD", e:234},
{b: 675, c: 555, d:"RRU", e:"SSS"},
{b: "TTT", c: 905, d:"PPP", e:"GGG"}
]
$ctrl.objArray2 =[
{b: "AAA", c: 555, d:"RRR", e:"YYY"},
{b: "TTT", c: 905, d:"PPP", e:"GGG"}
]
$ctrl.isInArray = function(obj, objArray) {
return objArray.findIndex((el) => {
return angular.equals(obj, el);
}) >= 0;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as $ctrl">
<table>
<tr ng-repeat="objs in $ctrl.objArray1">
<td>{{objs}}</td>
<td><input type="checkbox" id="{{$index}}" ng-checked="$ctrl.isInArray(objs, $ctrl.objArray2)" /></td>
</tr>
</table>
</div>
推荐阅读
- django-models - 在 Django APIView 中从/向相关表检索和发布数据
- function - 启用/禁用离线文件同步
- java - 如何修复错误:processDebugMainManifest DEBUG
- asp.net-mvc - 迁移 asp.net 核心身份以将数据保护与 SQL DB 一起使用
- amd - AMD Radeon - 更新
- html - 使用 Quill Editor 格式化 html
- c++ - C++:删除动态变量
- type-inference - 当想要针对错误消息进行优化时,Hindley Milner 类型推断的最佳算法是什么
- javascript - 用初始值减少javascript
- node.js - 如何将 json 中的图像渲染到图像文件 url