2016-07-01 4 views
1

어떻게 ng-repeat를 사용하여 다음 구조를 만들 수 있습니까? 솔루션은 임의의 깊이를 지원해야합니다 ...AngularJS : 중첩 된 div를 작성하는 방법은 무엇입니까?

ng-repeat-start & ng-repeat-end로 재생했지만 지금까지 행운이 없습니다. 어떤 힌트는 크게

<div>1 
    <div>2 
     <div>3</div> 
    </div> 
</div> 
+0

, 당신은하려고 더 좋을 수 있습니다 중첩 된 지시문을 사용하여이를 수행하십시오. http://stackoverflow.com/questions/14430655/recursion-in-angular-directives를 참조하십시오. –

답변

1

이 중첩 된 객체의 값을 렌더링하기 위해 NG 반복을 활용하는 지침을 통해 달성 될 수 appriciated됩니다. 보기 작동 here.

지침

app.directive('divRepeater', function($compile) { 
    return { 
    restrict: 'E', 
    replace: true, 
    template: '<ul></ul>', 
    scope: { 
     obj: '=' 
    }, 
    link: function(scope, element) { 
     var el = angular.element('<span/>'); 
     el.append('<li>' + scope.obj.id + '</li>'); 
     if (scope.obj.nestedObjs) { 
     var nestedObjs = angular.toJson(scope.obj.nestedObjs); 

     /// remove quotes from property names 
     nestedObjs = nestedObjs.replace(/\"([^(\")"]+)\":/g, "$1:"); 

     var nestedDir = "<div ng-init='nestedObjs=" + nestedObjs + "'><div-repeater ng-repeat='nestedObj in nestedObjs track by $index' obj='nestedObj'></div-repeater></div>"; 
     el.append(nestedDir); 
     } 
     $compile(el)(scope); 
     element.append(el); 
    } 
    }; 
}); 

컨트롤러

app.controller('MainCtrl', function($scope) { 
    $scope.objs = [{ 
    id: '1', 
    nestedObjs: [{ 
     id: 'a' 
    }, { 
     id: 'b', 
     nestedObjs: [{ 
     id: 'i' 
     }, { 
     id: 'ii' 
     }] 
    }] 
    }, { 
    id: '2' 
    }, { 
    id: '3', 
    nestedObjs: [{ 
     id: 'a', 
     nestedObjs: [{ 
     id: 'i' 
     }] 
    }, { 
     id: 'b', 
     nestedObjs: [{ 
     id: 'i' 
     }, { 
     id: 'ii' 
     }] 
    }] 
    }]; 
}); 

마크 업 NG-반복 루핑

<div-repeater ng-repeat="obj in objs track by $index" obj="obj"></div-repeater> 
관련 문제