Why is this function executed twice?

I have a tree structure. Jsbin here

in the directive

scope.add_child_task = function() { scope.add_task(scope.path,"child of " + scope.member.name); if (!scope.has_children) { scope.add_children_element(); scope.has_children = true; } }; 

in the controller

 $scope.add_task = function(to,name) { DataFactory.add_task(to,name); }; 

factory finds the correct position and adds node.

When adding a child node to nodes with existing children, it adds two children, and I don’t understand why.

Thanks.

EDIT I can lose has_children and it still gives the same result

updated jsbin

Member link functin

 link: function (scope, element, attrs) { element.append("<collection></collection>"); $compile(element.contents())(scope); scope.get_path = function() { var temp = scope.$parent.get_path(); temp.push(scope.member.name); return temp; }; scope.path = scope.get_path(); scope.add_child_task = function() { scope.add_task(scope.path,"child of " + scope.member.name); }; } 

EDIT 2 Dropped the for loops too - just exchanging links, there was nothing left but a function executed twice!

updated jsbin

+7
javascript angularjs
source share
1 answer

You compile the whole element (including the added part of the directive template that has already been compiled):

 element.append("<collection></collection>"); $compile(element.contents())(scope); 

Since your click handler is in the template , compiling the template, a second set of click handlers is added a second time (among other things).

 template: "<li>{{member.name}}" + " <i>{{path}}</i> <a href ng-click='add_child_task()'>Add Child</a></li>", 

Bugfix: Instead, use this to compile only the new item that you added:

 newe = angular.element("<collection></collection>"); element.append(newe); $compile(newe)(scope); 

updated jsbin

+3
source share

All Articles