2014-10-05 97 views
0

我想创建一个角树指令,这里是代码:AngularJS指令范围继承

//** 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样式看起来不正确,因为$scope.selectedNode仅影响treeChildren指令中的自己的作用域。

如何从主指令范围执行范围继承?因为我希望每个节点点击都会访问全球$scope.selectedNode

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

希望我解释清楚,因为我可怜的英语

回答

0

你的代码有几个错误。我建议在控制器上尝试使用别名语法,而不是通过它们。

它会简化你的代码,并可能澄清你正在尝试做什么。

别名语法可以避免直接注入$ scope,并使得更清晰地使用哪个控制器。

Check this awesome explanation out

我希望它有帮助。

+0

感谢您的回复。这是一个旧的帖子,我现在使用'as'语法。但我仍然不清楚指令继承。稍后将更新代码。 – Neaped 2015-02-02 02:45:55