在我的 Controller 中,我有一个从 Java Controller 接收对象的函数。我的 AngularJS 变量很简单:
var self = this;
self.item = {};
以及我获取对象的函数:
function getItem() {
MyService.getItem(REST_SERVICE_URI)
.then(
function (d) {
self.item = d;
},
function (errResponse) {
console.error('Error while getting item');
}
);
}
接收到的对象结构相当复杂。它有 id、name 和子对象列表,子对象也有 id 和 name 字段。如何进入该对象的字段并在 AngularJS Controller 中列出?我尝试使用下面的函数循环遍历列表,甚至计算重复值,但它不起作用。我什至尝试在其中再包含一个循环,并在控制台中输出结果,但没有效果。它只返回零。
var i = "SOME TEST NAME VALUE TO CHECK";
function getCount(i) {
var iCount = iCount || 0;
for (var el in self.item) {
console.log("let me see what are you: " + el);
if (el == i) {
iCount++;
}
}
return iCount;
}
我收到的对象没问题,我可以使用 F12 - 网络 - 响应或预览在 Chrome 中查看它的内容。
稍后添加: 在我的页面上我这样测试
<tr class="my_item" ng-repeat="p in ctrl.item.children">
<span>getCount {{p.name}}: {{ctrl.getCount(p.name)}}</span>
</tr>
它在跨度中显示 p.name 顺便说一句。 Java对象结构为
public class Item {
private int id;
private String name;
List<Child> children = new ArrayList<>();
}
子类很简单
public class Child {
private int id;
private String name;
}
最佳答案
根据您的问题,内容很复杂,并且子内容内具有递归属性
。
因此,您需要在一个 forEach 循环
内递归地
迭代内容。
查看此示例演示:
var myApp = angular.module('myApp', []);
myApp.controller('ExampleController', function() {
var vm = this;
vm.count = 0;
vm.searchTxt = "";
vm.getCount = function() {
vm.count = 0; //clear count before search
recursive(vm.content);
}
function recursive(dataArray) { //recursive function
dataArray.forEach(function(data) {
if (vm.searchTxt == data.name) { //match name property
vm.count = vm.count + 1;
}
if (data.child.length > 0) {
recursive(data.child); // call recursive function
}
});
}
vm.content = [{ //example content
id: 1,
name: 'one',
child: [{
id: 1.1,
name: 'new one',
child: [{
id: 1,
name: 'one',
child: []
}]
}]
}, {
id: 2,
name: 'two',
child: [{
id: 1.1,
name: 'new two',
child: []
}]
}]
});
<script src="https://code.angularjs.org/1.5.2/angular.js"></script>
<div ng-app="myApp" ng-controller="ExampleController as vm">
<input ng-model="vm.searchTxt" placeholder="ender search.." />
<br>
<button ng-click="vm.getCount()">Search</button>
<br>
<span>Match 'Name' count : {{vm.count}}</span>
</div>
关于javascript - 我如何处理发送到 AngularJS Controller 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44547920/