angularjs Treeview using ng-include fires ng-click for all node's parents

对着背影说爱祢 提交于 2019-12-12 03:24:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!