Reputation: 4147
I have a tree structure like this stored in the $scope.tree
object. I want to create a filter, that I could apply to this tree to shrink it to this to be able to do smth like this $scope.cut_tree = $filter('cutTree')($scope.tree)
and get that minified output.
But I have really no idea how to do that, everything I've tried so far does not get me anywhere, 'cause I end up changing the $scope.tree itself.
UPDATE
What I have so far:
app.filter("filterTree", ["$filter", function($filter) {
return function(tree) {
var newTree = [];
angular.forEach(tree, function(node, index) {
var newNode;
newNode = {
id: node.id,
sort_order: index,
children: $filter('filterTree')(node.children)
};
newTree.push(newNode);
});
return newTree;
};
}
]);
Upvotes: 2
Views: 4090
Reputation: 2246
I've made a working example in this JsFiddle.
The filter used is the following :
angular.module('myApp').filter('cutTree', ['$filter',function ($filter) {
return function (tree) {
var res = [];
var sortOrder=0;
angular.forEach(tree, function(item) {
// Deep copy
var copy = angular.fromJson(angular.toJson(item))
res.push({
id:copy.id,
sort_order:sortOrder,
children:$filter('cutTree')(item.children)
})
sortOrder++;
});
return res;
};
}]);
Upvotes: 1
Reputation: 196
It should be relatively easy to make a recursive function that only copies over the field you want. for example
var cutTree = function(original){
var result = {};
result.id = original.id;
result.name = original.name;
result.children = [];
for (var i=0; i<original.children.length; i++)
{
result.children.push(cutTree(original.children[i]));
}
return result;
}
Then you only need to define a filter that will call this function and return its result.
Upvotes: 1