AngularJS kendo treeview以编程方式选择子节点

时间:2017-07-04 02:31:10

标签: angularjs kendo-ui treeview

基于以下代码,如果我提供的id属于父节点,我可以在树视图中选择节点,例如:1。但是当我提供子节点的id时,例如:2.1,它是无法从代码级别选择节点。 以下是我目前使用的代码:

<div id="example" ng-app="KendoDemos">
    <div class="demo-section k-content" ng-controller="MyCtrl">
        <div class="box-col">
            <h4>TreeView</h4>
            <div kendo-tree-view="tree"
                k-data-source="treeData"
                k-on-change="selectedItem = dataItem">
                <span k-template>
                    {{dataItem.text}}
                </span>
            </div>
        </div>
    </div>
</div>


angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", ["$scope", "$timeout", function($scope, $timeout) {
      $scope.treeData = new kendo.data.HierarchicalDataSource({
          data: [
              { text: "Item 1", id: 1 },
              { text: "Item 2", id: 2, items: [
              { text: "SubItem 2.1", id: 2.1 },
              { text: "SubItem 2.2", id: 2.2 }
          ] },
          { text: "Item 3", id: 3 }
      ]});

      $scope.click = function(dataItem) {
        alert(dataItem.text);
      };

      $scope.selectNode = function(id) {
          $scope.branchId = id;
          var item = $scope.treeData._data.find(findKendoBranchById);
          var node = $scope.tree.findByUid(item.uid);
          $scope.tree.select(node);
      }

      function findKendoBranchById(item, index, kendo) {
          var isThisBranch = false;

          if (item.id == null) {
              isThisBranch = item.text == $scope.branchId;
          } else {
              isThisBranch = item.id == $scope.branchId;
          }

          return isThisBranch;
      }

      $timeout(function() {
          $scope.selectNode(2);
          //when this runs, will show the error below
          $scope.selectNode(2.1); 
      }, 2000);
  }]);

VM1703 angular.min.js:107 TypeError: Cannot read property 'uid' of undefined
at n.$scope.selectNode (<anonymous>:20:50)
at <anonymous>:38:18
at VM1703 angular.min.js:146
at e (VM1703 angular.min.js:43)
at VM1703 angular.min.js:45

1 个答案:

答案 0 :(得分:1)

最后,我选择在更改所选节点时重新启动树视图。

$scope.rawData = [
   { text: "Item 1", id: 1 },
   { text: "Item 2", id: 2, items: [
      { text: "SubItem 2.1", id: 2.1 },
      { text: "SubItem 2.2", id: 2.2 }
      ]
   }];
$scope.selectNode = function(id){
   $scope.treeData = new kendo.data.ObservableArray(processSelectedNode($scope.rawData, id));
};

function processSelectedNode(array, id){
    var navigationData = [];

    for (var i = 0; i < array.length; i++) {
       var obj = array[i];
       obj.expanded = true;
       obj.selected = obj.id == id;

       if (array[i].items) {
           obj.items = prepareNavigationTreeDataSource(array[i].items, id);
        }

        navigationData.push(obj);
    }
}

这适用于我,因为Kendo Treeview将选择具有selected = true

的节点