AngularJS指令范围继承

时间:2014-10-05 19:10:30

标签: javascript angularjs angularjs-scope

我正在尝试创建一个角度树指令,这里是代码:

//** Tree constructor
var Tree = function() {
  return {
    restrict: 'EA',
    replace: true,
    template: "<ul>" +
                "<li ng-repeat=\"node in node.children\">" +
                "<a ng-click=\"selectNode(node)\" ng-class=\"{selected: isSelected(node)}\">" +
                  "{{node.name}}" +
                "</a>" +
                "<tree-children></tree-children>" +
                "</li>" +
              "</ul>",
    scope: {
      treeData: '='
    },
    controller: function($scope) {
        //** Selected Node
        $scope.selectedNode = null;

        //** Node on click
        $scope.selectNode = function(node) {
            if ($scope.selectedNode !== node) {
              $scope.selectedNode = node;
            } else {
              $scope.selectedNode = null;
            }
        };

        $scope.isSelected = function(node) {
            return (node === $scope.selectedNode);
        }

    },
    link: function(scope, elem, attrs) {

      //** Watch
      scope.$watch('treeData', function(data) {
        if (angular.isArray(data)) {
          scope.node = {};
          scope.node.children = data;
        } else {
          //***********
        }
      });
    }
  }
}

//** Tree children constructor
var TreeChildren = function($compile) {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {

      var childScope = scope.$new(),
          template = '<tree tree-data="node.children"></tree>',
          content = $compile(template)(childScope);

      //** Append
      elem.append(content);
    }
  };
};

TreeChildren.$inject = ['$compile'];

//** Angular Module
angular
.module('app', [])
.directive('tree', Tree)
.directive('treeChildren', TreeChildren)
.controller('treeCtrl', ['$scope', function($scope) {
  $scope.treeData = [
        {
            name: 'Root',
            children: [
                {
                    name: 'Node-1',
                    children: [
                        { name: 'Node-1-1'},
                        { name: 'Node-1-2'},
                        { name: 'node-1-3'}
                    ]
                },
                {
                      name: 'Node-2',
                      children: [
                        { name: 'Node-2-1'}
                      ]
                }
            ]
        }
    ];
}]);

Plunker link

我遇到了将$scope.selectedNode设置为全局的问题,现在如果单击树节点,则css样式看起来不正确,因为{ {1}}仅影响$scope.selectedNode指令中的自身范围。

如何从主指令范围进行范围继承?因为我希望每个节点点击都会访问全局 treeChildren

我已经对Understanding Scopes做了一些阅读,但仍然感到困惑。

希望我能解释清楚,因为我的英语很差

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。我建议您尝试在控制器上使用别名语法,而不是通过它们。

它将简化您的代码,并可能澄清您正在尝试做的事情。

别名语法避免直接注入$ scope并使得哪个控制器正在使用更清楚。

Check this awesome explanation out

我希望它有所帮助。