【问题标题】:Error in listing tree structure using ng-repeat in angularjs在angularjs中使用ng-repeat列出树结构时出错
【发布时间】:2015-04-18 19:20:58
【问题描述】:

我正在尝试使用 ng-repeat 在 html 上列出嵌套字典

这是完整的code

但似乎我无法访问字典键的值

tree.value

因为它要么不显示,要么只会打印

'tree.value'

谁能帮帮我?

<div ng-app>
  <script type="text/ng-template" id="myTemplate">
      <li>X</li>
      <p>1 tree.value</p>
      <ul ng-repeat="tree in tree.children" ng-include="'myTemplate'">
          <p>2 tree.value</p>
      </ul>
  </script>
 <div>
     <ul ng-include="'myTemplate'"
    ng-init="tree = 
               {
        children: 
            [
                {children: [], value: c12}, 
                {
                    children: 
                        [
                            {children: [], value: c112}, 
                            {children: [], value: c111}
                        ],
                    value: c11
                }
            ], 
        value: c1
    }
"></ul>
  </div>
</div>

【问题讨论】:

    标签: javascript html angularjs tree angularjs-ng-repeat


    【解决方案1】:

    您的 json 定义错误,您应该始终将字符串值包含在单引号 ' 中,例如 value: c111value: 'c112' 值应该像 value: 'c111'value: 'c112' 一样

    标记

        <ul ng-include="'myTemplate'"
            ng-init="tree = 
                       {
                children: 
                    [
                        {children: [], value: 'c12'}, 
                        {
                            children: 
                                [
                                    {children: [], value: 'c112'},
                                    {children: [], value: 'c111'}
                                ],
                            value: c11
                        }
                    ], 
                value: c1
            }
    "></ul>
    

    最好在$scope 中定义tree 变量而不是在html 上。

    Working JSFiddle

    【讨论】:

    • 你知道为什么{{tree.value}} 必须在ul 标签之外而不是在ul 标签内吗?
    • @Kevin 因为当&lt;ul ng-repeat="tree in tree.children" ng-include="'myTemplate'"&gt; 标签没有tree.childrenul 不会被ng-repeat 渲染,这就是为什么它应该在ul 之外
    【解决方案2】:

    似乎 c1 是对象而不是字符串。所以 c1 具有属性。例如 c1 具有文本属性。

    你应该写在模板 {{tree.value.text}}

    【讨论】:

      猜你喜欢
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      相关资源
      最近更新 更多