3

我想$scope在 AngularJS 控制器中使用一个变量,如下所示:

$scope.hierarchy = {
  name: 'bob',
  selected: true,
  children: [
    { name: 'frank' },
    {
      name: 'spike',
      children: [
        { name: 'mike' },
        { name: 'ben' },
        { name: 'gloria' },
      ]
    },
    {
      name: 'lisa',
      selected: true,
      children: [
        { name: 'bobby' },
        { name: 'carol' },
        { name: 'roger' },
      ]
    },
  ]
}

填充模板。问题是,我想在一个框中列出一个级别的所有内容,并为所选项目的子项添加一个新框(想想 OSX Finder 的文件夹浏览)。

所以理想情况下,我会有一个角度模板,它可以呈现如下所示的内容:

+------+ +--------+ +-------+
| >bob | |  frank | | bobby |
+------+ |  spike | | carol |
         | >lisa  | | roger |
         +--------+ +-------+

从表面上看,这似乎是一项简单的任务,但我要么太厚而无法想到解决方案,要么问题比看起来更难。提前感谢您的帮助!

4

1 回答 1

0

基于 Cherniv 的示例, 这是一个工作小提琴。只需更改布局,您就可以看到,如果您将“selected: true”放在尖峰而不是 lisa 上,它会正确调整。

HTML:

<script type="text/ng-template"  id="tree_item_renderer.html">
    <ul>
        <li ng-repeat="data in data.children">
            {{data.name}}
            <ul>
                <span ng-switch on="data.selected">
                <div ng-switch-when="true" ng-include="'tree_item_renderer.html'">
                </li>
                </span>
            </ul>
        </li>
    </ul>
</script>

<div ng-controller="TreeController">
    <div ng-include="'tree_item_renderer.html'">
    </div>
</div>
</ul>

Javascript:

var myApp = angular.module("myApp", []);
myApp.controller("TreeController", ['$scope', function($scope) {
    $scope.data = {
        children: [{
          name: 'bob',
          selected: true,
          children: [
            { name: 'frank' },
            {
              name: 'spike',
              children: [
                { name: 'mike' },
                { name: 'ben' },
                { name: 'gloria' },
              ]
            },
            {
              name: 'lisa',
              selected: true,
              children: [
                { name: 'bobby' },
                { name: 'carol' },
                { name: 'roger' },
              ]
            }
          ]
        }]
    }

}]);
于 2013-10-18T21:59:17.720 回答