javascript - 使用 AngularJS 动态构建树

标签 javascript angularjs

我对 AngularJS 很陌生,所以我的问题可能非常微不足道,但我没有在网络上找到任何可以提供帮助的答案。

拥有 json 形式的数据,例如:

{
    "Part 1": {
        "Group 1": {
            "Link 1": "href1",
            "Link 2": "href2"
        },
        "Group 2": {
            "Link 3": "href3"
        }
    },
    "Part 2": {
        "Link 4": "href4",
        "Link 5": "href5",
        "Link 6": "href6"
    }
}

我想以树的形式呈现它。例如:

1. Part 1
    a. Group 1
        - Link 1
        - Link 2
    b. Group 2
        - Link 3
2. Part 2
    - Link 4
    - Link 5
    - Link 6

树的叶子代表可以单击的链接。可以有一层或两层嵌套,因此可能会有点问题。

是否可以使用 ngRepeat 指令或 AngularJS 的任何其他方式来做到这一点?

最佳答案

使用指令绝对是更合适的解决方案,但是如果您愿意,您可以使用 ng-repeat (尽管它不是最优雅的解决方案),请参阅 fiddle: http://jsfiddle.net/ADukg/4764/

你可以使用这样的东西:

<div ng-controller="MyCtrl">
  <div ng-repeat="(item, children) in data">
      {{item}}
      <div ng-repeat="(child, moreChildren) in children">
          <div class="child" ng-show="isGroup(child)">
              {{child}}
              <div class="leaf" ng-repeat="(leaf, leafValue) in moreChildren">
                  {{leaf}} - {{leafValue}}
              </div>
          </div>
          <div class="leaf" ng-show="!isGroup(child)">
              {{child}} - {{moreChildren}}              
          </div>
      </div>            
    </div>
</div>

使用基本检查器:

$scope.isGroup = function(item) {
    return item.indexOf('Group') == 0;      
};

关于javascript - 使用 AngularJS 动态构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21885965/

相关文章:

javascript - 用于 jasmine/karma 测试的 angularjs 中的全局模拟对象

javascript - 为什么 Div 元素在手动复制粘贴时看起来很好,但在附加 jquery append 时看起来很糟糕?

javascript - 具有 css 类的字符串的大小

javascript - 如何使用 jQuery 模拟输入事件?

javascript - 有效和无效电子邮件地址的正则表达式

javascript - Pubnub : How to estimate history chat messages count prior to calling ngHistory

javascript - 在 AngularJS 中使用调用 self 的函数来声明 Controller 有什么好处

javascript - 如果我将 null 除以 javascript/Angular 中的数字,如何得到 null?

angularjs - Angular UI Bootstrap 模态

javascript - 如何将 CSV 文件导入 web 应用程序的 javascript,以便我可以在谷歌地图 Canvas 上放置地址标记?