javascript - Angular JS: Why is my click event firing twice? -
i have following code. loops on json produce nested ul list. have click event executes function togglenav() bound anchor tag. don't know why click event bound twice element. new angular, there document explains concept out there? thanks!
define([ '/assets/angularapp/appdirectives.js', 'highstock' ], function (directives) { directives.directive('collection', function () { return { restrict: "e", //declare element replace: true, scope: { collection: '=' }, template: "<ul class=\"nav nav-list tree\"><member ng-repeat=\"member in collection\" member=\"member\"></member></ul>" } }) directives.directive('member', function ($compile) { return { restrict: "e", replace: true, scope: { member: '=' }, template: "<li ng-show=\"member.open\"><span><input type=\"checkbox\" ng-model=\"member.selected\" class=\"sidechkbox\"><a class=\"tree-toggle\" ng-click=\"togglenav()\"><i class=\"icon-chevron-right\"></i>{{member.data}}</a></span></li>", controller: function($scope, $element){ $scope.togglenav = function(){ angular.foreach($scope.member.children,function(child,key){ if(child.open==true){ alert("a") child.open=false; } else { child.open=true; alert("b") } }) } }, link: function (scope, element, attrs) { if (angular.isarray(scope.member.children)) { element.append("<collection collection='member.children'></collection>"); $compile(element.contents())(scope) } } } })
it because compiling element.contents(), including <a> ng-click, should compiled. @ time call manual compile, gets compiled again.
you can fix this:
... if (angular.isarray(scope.member.children)) { var newmemel = angular.element("<collection collection='member.children'></collection>"); element.append(newmemel); $compile(newmemel)(scope); } ...
it looks trying create treeview, in case, better use nginclude instead of creating custom directives, have @ plunker, note not work angular 1.2.0rc1 due issue
Comments
Post a Comment