我想使用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'
}
];
});
这是输出图片:
例如,当选择paridokht节点时,警报层次结构按顺序为paridokht、macbooks、笔记本电脑,计算机(从 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/