我正在创建一个“树”导航,我遇到了嵌套子项的问题,服务器向我发送了如下所示的JSON数据:
JSON :
0: {id:5, parentid:0, text:PlaceHolder}
1: {id:6, parentid:0, text:PlaceHolder}
2: {id:7, parentid:0, text:PlaceHolder}
3: {id:8, parentid:7, text:PlaceHolder}
4: {id:9, parentid:7, text:PlaceHolder}
5: {id:10, parentid:5, text:PlaceHolder}
6: {id:11, parentid:5, text:PlaceHolder}
7: {id:12, parentid:7, text:PlaceHolder}
8: {id:15, parentid:0, text:PlaceHolder}
9: {id:16, parentid:15, text:PlaceHolder}
10: {id:17, parentid:5, text:PlaceHolder}
11: {id:18, parentid:15, text:PlaceHolder}
12: {id:19, parentid:15, text:PlaceHolder}
13: {id:20, parentid:0, text:PlaceHolder}
14: {id:21, parentid:15, text:PlaceHolder}
15: {id:23, parentid:5, text:PlaceHolder}
注意'parentid'。 “0”表示该项目是顶级父级。例如,如果'parentid'为7,那么它将是'id'7的孩子。
HTML:
<li ng-repeat="link in links"><a href="#/page/{[{link.id}]}">{[{link.text}]}</li>
JS:
var Site = angular.module('Site', []);
Site.config(function ($routeProvider) {
$routeProvider
.when('/page/:slug', {templateUrl: 'partials/page.html', controller: 'RouteController'})
.otherwise({redirectTo: '/page/home'});
});
function AppController ($scope, $rootScope, $http) {
/* Load pages on startup
$http.get('pages.json').success(function (data) {
$rootScope.pages = data;
}); */
// Load navigation on startup
$http.get('/university/list').success(function (data) {
$rootScope.links = data;
});
// Set the slug for menu active class
$scope.$on('routeLoaded', function (event, args) {
$scope.slug = args.slug;
});
}
function RouteController ($scope, $rootScope, $routeParams) {
// Getting the slug from $routeParams
var slug = $routeParams.slug;
$scope.$emit('routeLoaded', {slug: slug});
$scope.page = $rootScope.pages[slug];
}
答案 0 :(得分:2)
我尝试做这样的事情http://jsfiddle.net/zzal/qdvuN/10/ ...从你在IRC频道上的问题这里设置菜单的方式:
尝试在数组中获取JSON响应:
var PlaceHolder = "PlaceHolder";
var myArr =
[{id:5, parentid:0, text:PlaceHolder},
{id:6, parentid:0, text:PlaceHolder},
{id:7, parentid:0, text:PlaceHolder},
{id:8, parentid:7, text:PlaceHolder},
{id:9, parentid:7, text:PlaceHolder},
{id:10, parentid:5, text:PlaceHolder},
{id:11, parentid:5, text:PlaceHolder},
{id:12, parentid:7, text:PlaceHolder},
{id:15, parentid:0, text:PlaceHolder},
{id:16, parentid:15, text:PlaceHolder},
{id:17, parentid:5, text:PlaceHolder},
{id:18, parentid:15, text:PlaceHolder},
{id:19, parentid:15, text:PlaceHolder},
{id:20, parentid:0, text:PlaceHolder},
{id:21, parentid:15, text:PlaceHolder},
{id:23, parentid:5, text:PlaceHolder}];
现在,创建嵌套数组来保存“子”对象:
for (var i = 0; i < myArr.length; i++){
myArr[i].children = [];
for (var q = 0; q < myArr.length; q++){
if (myArr[i].id == myArr[q].parentid){
// if want to keep the parentid key
//var temp = {id:myArr[q].id,parentid:myArr[q],text:myArr[q].text}
var temp = {id:myArr[q].id,text:myArr[q].text};
myArr[i].children.push(temp);
};
};
};
现在,您的数组myArr
应该以新的键阵列children
结束,并且需要遵循示例所需的布局。