问题
I want to write treeview
using angularjs
. I am using ng-include
for recursive
call..everything is fine except from ng-click
..when each node is clicked..the hierarchy call is from child to it's parents and for every node in this hierarchy the ng-click
fires. how can i solve this problem??..I have this exact problem using another approach (appending element on post-link
which I think is not a good way) instead of ng-include
.
here is my code:
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>
template.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'
}
];
});
here is the output picture:
for example when paridokht node is selected, the alert hierarchy in order is paridokht,macbooks,laptops,computers (from child to parents).
please help me to solve this issue. it's killing me! :(
回答1:
Try stopping event from bubble-ing up in the DOM tree.
In you ng-click
:
ng-click='nodeSelected($event, category)'
In your controller:
$scope.nodeSelected = function($event, category){
$event.stopPropagation();
alert('This node is selected' + category.title);
}
来源:https://stackoverflow.com/questions/34848984/angularjs-treeview-using-ng-include-fires-ng-click-for-all-nodes-parents