如何使用指令的模板渲染树结构数据

时间:2013-03-25 07:52:50

标签: angularjs angularjs-directive

有没有人试图通过使用指令来渲染树结构数据?

我想要做的是渲染数据......

{ 
  name: "root", 
  next: null,
  child: {
    name : "1"
    next : {
      name : "2",
      next : {
        name: "3",
        next: null,
        child: null
      }, 
      child: {
        name: "2-1",
        next: null,
        child: null
      }
    },
    child: {
      name: "1-1",
      next: {
        name: "1-2",
        next: null,
        child: null
      },
      child: null
    }
  }
}

到HTML数据,如

<ul>
  <li> root 
    <ul>
      <li> 1 
        <ul>
          <li> 1-1 </li>
          <li> 1-2 </li>
        </ul>
      </li>
      <l1> 2 
        <ul>
          <li> 2-1 </li>
        </ul>
      </li>
      <li> 3 </li>
    </ul>
  </li>
</ul>

我知道如果数据是数组,我可以使用“ng-repeat”作为模板, 如果数据是我知道结构的对象,我可以使用“{{}}”标记。

但我不知道处理对象数据会动态变化。 这意味着我还想在数据中添加一些子作为$ scope中的一个对象, 并使用angular.js同步渲染。

有没有人有一个好主意或你做过的经验?

1 个答案:

答案 0 :(得分:-1)

angularjs

<div ng-init="friends = [
  {name:'John', age:25, gender:'boy'},
  {name:'Jessie', age:30, gender:'girl'},
  {name:'Johanna', age:28, gender:'girl'},
  {name:'Joy', age:15, gender:'girl'},
  {name:'Mary', age:28, gender:'girl'},
  {name:'Peter', age:95, gender:'boy'},
  {name:'Sebastian', age:50, gender:'boy'},
  {name:'Erika', age:27, gender:'girl'},
  {name:'Patrick', age:40, gender:'boy'},
  {name:'Samantha', age:60, gender:'girl'}
]">     

  <ul class="example-animate-container">
    <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
      [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
    </li>
  </ul>
</div>

结果

[1] John who is 25 years old.
[2] Jessie who is 30 years old.
[3] Johanna who is 28 years old.
[4] Joy who is 15 years old.
[5] Mary who is 28 years old.
[6] Peter who is 95 years old.
[7] Sebastian who is 50 years old.
[8] Erika who is 27 years old.
[9] Patrick who is 40 years old.
[10] Samantha who is 60 years old.