角度递归指令和ngRepeat范围

时间:2015-07-22 14:53:53

标签: javascript angularjs recursion tree hierarchical-data

我遇到了角度递归树指令的问题,我的ngRepeat由于某种原因没有在范围内得到模型,下面是我的指令代码。

app.controller("PageController", function($scope) {

这是我的数据对象:

  $scope.myTree = [{
    "name": "Apparel",
    "checked": false,
    "children": [{
      "name": "Mens Shirts",
      "children": [{
        "name": "Mens Special Shirts",
        "children": []
      }]
    }, {
      "name": "Womens Shirts",
      "children": []
    }, {
      "name": "Pants",
      "children": []
    }]
  }, {
    "name": "Boats",
    "children": []
  }];
});

主要指示:

app.directive("treeUi", function($compile, $timeout) {
  return {
    priority: 1001,
    replace: false,
    transclude: "element",
    restrict: "AEC",
    scope: {
      tree: "=ngModel"
    },
    link: function(scope, el, attrs, ctrl, transclude) {
      var transcludedContent, compiler, itemElement;

      transclude(function(clone, tScope) {
        // trying to create $scope.treeItem inside ngRepeat
        itemElement = clone.find("li").attr("tree-element", "").attr("ng-repeat", "treeItem in tree");
        transcludedContent = clone;
        el.after(clone);
      });
      $compile(itemElement)(scope);
    }
  };
});

子元素指令

app.directive("treeElement", function($compile) {
  return {
    priority: 1002,
    replace: false,
    restrict: "AEC",
    compile: function(tElement, tAttrs) {
      return function linker(scope, element) {

我从未在这里获得scope.treeItem

        console.log(scope.treeItem); // gives me undefined
        scope.$watch("treeItem", function(newVal) {
          console.log(newVal); // nothing here either
        });

        // This will append a sub-menu to my li, if model has children
        if (scope.treeItem && scope.treeItem.children.length) {
          var childTree = $compile('<ul tree-ui ng-model="treeItem.children"></ul>')(scope);
          element.append(childTree);
        }
      };
    }
  };
});

这就是我的html的样子:

            <ul tree-ui ng-model="myTree">
                <li>
                    <a href="">{{treeItem.name}}</a>
                </li>
            </ul>

关于发生了什么的任何建议?

0 个答案:

没有答案