我正在尝试确定正确的方式或 Angular 方式来为构建 DOM 的指令提供数据。作为我的示例,我正在尝试从文件中获取 JSON 数据以使用 jsTree 构建树。问题是在数据到达时而不是事先构建树。
$watch我已经通过在我的treeData控制器中解决了这个问题。如果我不这样做$watch,树将使用一个空数组作为输入来构造,稍后,Angular 将更新引用以填充数据。但我觉得这是错误的做法,因为在最初构建树后数据不会改变。
这是我的代码
应用程序.js:
var app = angular.module('jsTreeApp', ['ngResource']);
var TestCtrl = function($scope, Data) {
  $scope.treeData = Data.getTreeData();
}
app.directive('jstree', function() {
  return function(scope, element) {
    scope.$watch('treeData.data', function() {
      $(element).jstree({
        "json_data" : scope.treeData,
        "plugins" : [ "themes", "json_data" ]
      });
    })
  }
});
app.factory('Data', function($resource) {
  return $resource('/data/treeData.json', {}, {
    getTreeData: { method: 'GET', isArray: false }
  })
})
索引.html:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jsTreeAngular</title>
</head>
<body>
<div ng-controller="TestCtrl" ng-app="jsTreeApp">
  <div jstree></div>
</div>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="lib/jstree/jquery.jstree.js"></script>
</body>
</html>
对正确的方法有什么建议吗?