javascript - 使用 ng-include 的 angularjs Treeview 为所有节点的父节点触发 ng-click

标签 javascript angularjs recursion treeview event-propagation

我想使用angularjs编写treeview。我正在使用 ng-include 进行递归调用..除了 ng-click 之外一切都很好..单击每个节点时..层次结构调用是从子级到其父级,并且对于该层次结构中的每个节点,ng-click 都会触发。我该如何解决这个问题??..我使用另一种方法(在 post-link 上附加元素,我认为这不是一个好方法)来解决这个问题,而不是 ng-include
这是我的代码:

index.html:

    <!doctype html>
<html>    
    <head>       
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.0/angular.min.js"></script>    
    </head>
    <body >   
        <div ng-app="app" ng-controller='AppCtrl'>    
    <ul>
        <li ng-repeat="category in categories" ng-click='nodeSelected(category)' ng-include="'template.html'"></li>
    </ul>    
</div>    
    <script src="controller.js"></script>

    </body>
</html>

模板.html:

{{ category.title }}
    <ul ng-if="category.categories">
        <li ng-repeat="category in category.categories" ng-click='nodeSelected(category)' ng-include="'template.html'">{{ category.title }}</li>
    </ul>

Controller .js

    var app = angular.module('app', []);
app.controller('AppCtrl', function ($scope) {

$scope.nodeSelected = function(category){
    alert('This node is selected' + category.title);
}
$scope.categories = [
  { 
    title: 'Computers',
    categories: [
      {
        title: 'Laptops',
        categories: [
          {
            title: 'Ultrabooks'
          },
          {
            title: 'Macbooks', 
              categories:[
              {
              title:'Paridokht'
          },
            {
                title:'Shahnaz',
                categories:[
                    {
                        title:'Sohrab'
                    }
                ]
            }
              ]
          }
        ]
      },
      {
        title: 'Desktops'
      },
      {
        title: 'Tablets',
        categories: [
          { 
            title: 'Apple'
          },
          {
            title: 'Android'
          }
        ]        
      }
    ]
  },

  {
    title: 'Printers'
  }
];
});


这是输出图片:

enter image description here
例如,当选择paridokht节点时,警报层次结构按顺序为paridokhtma​​cbooks笔记本电脑计算机(从 child 到 parent )。
请帮我解决这个问题。这太痛苦了! :(

最佳答案

尝试阻止事件在 DOM 树中冒泡。

在你ng-click中:

ng-click='nodeSelected($event, category)'

在你的 Controller 中:

$scope.nodeSelected = function($event, category){
    $event.stopPropagation();
    alert('This node is selected' + category.title);
}

关于javascript - 使用 ng-include 的 angularjs Treeview 为所有节点的父节点触发 ng-click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34848984/

相关文章:

javascript - 使用 Angular.JS 将 JSON 导入 HTML(错误)!

html - 如何在 Angularjs 中对 [Array] 值元素进行排序?

java - 递归 - 线程 "main"java.lang.StackOverflowError 中出现异常

c# - javascript 正则表达式的正则表达式

javascript - 获取函数中输入变量的名称

javascript - 如何阻止/允许访问 document.styleSheets 信息,这是什么原因

function - 如何在方案中重新创建申请

javascript - 将参数传递给backbone fetch url以处理非标准api

javascript - 如何创建一个根据参数使用 $resource 返回数据的服务

python - 递归查找n维数组的相邻坐标