简体   繁体   English

为什么这个函数执行了两次?

[英]Why is this function executed twice?

I've got a tree structure. 我有一个树形结构。 JSBIN here JSBIN在这里

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);
};

The factory is finding the correct position and adding the node. 工厂正在找到正确的位置并添加节点。

When adding a child to nodes with existing children it's adding two children and i don't understand why. 将子项添加到具有现有子项的节点时,它会添加两个子项,我不明白为什么。

Thanks. 谢谢。

EDIT I can lose has_children and it still produces the same result 编辑我可能失去has_children ,它仍然会产生相同的结果

updated JSBIN 更新了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 Droped the for loops as well - just exchanging references, nothing left but a function being executed twice ! 编辑2也改变了for循环 - 只是交换引用,没有剩下任何东西,但是一个函数被执行两次!

updated JSBIN 更新了JSBIN

You're compiling the entire element (including the part added by the directive's template, which 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 time results in a second set of click handlers (amongst other things) being added. 由于您的点击处理程序位于模板中,第二次编译模板会导致添加第二组点击处理程序 (以及其他内容)。

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

The Fix: Instead use this to compile only the new element you've added: 修复:而是使用它来仅编译您添加的新元素:

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

updated jsbin 更新了jsbin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM