In my controller I have a function that recieves an object from Java controller. My AngularJS variable is simple:
var self = this;
self.item = {};
And my function where I get the object:
function getItem() {
MyService.getItem(REST_SERVICE_URI)
.then(
function (d) {
self.item = d;
},
function (errResponse) {
console.error('Error while getting item');
}
);
}
Object that's received has rather complicated structure. It has id, name and list of child objects, who have also id and name fields. How do I get into this object's fields and list in the AngularJS controller? I tried loop though list using fucntion below to even count duplicate values but it didn't work. I tried even to include one more loop into it with outputing result in console, no effect. It only returns zeros.
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;
}
The object I recieve is ok, I can see it content in Chrome using F12 - Network - Response or Preview.
added later: On my page I test it like this
<tr class="my_item" ng-repeat="p in ctrl.item.children">
<span>getCount {{p.name}}: {{ctrl.getCount(p.name)}}</span>
</tr>
It displays p.name in the span btw. Java object structure is
public class Item {
private int id;
private String name;
List<Child> children = new ArrayList<>();
}
Child class is simple
public class Child {
private int id;
private String name;
}
As per your question, the content is complex and has recursive properties inside child content
.
So you need to iterate on content recursively
, inside one forEach loop
.
See this example working Demo :
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.