为什么这个函数执行两次? [英] Why is this function executed twice?
问题描述
我有一个树形结构。 JSBIN这里
I've got a tree structure. JSBIN here
在指令
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;
}
};
在控制器
$scope.add_task = function(to,name) {
DataFactory.add_task(to,name);
};
工厂找到正确的位置,并添加节点。
The factory is finding the correct position and adding the node.
当增加一个孩子与现有的儿童它增加了两个孩子,我不明白为什么到节点。
感谢。
修改
我可以失去 has_children
,它仍然产生相同的结果。
EDIT
I can lose has_children
and it still produces the same result
会员链接载体作用
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);
};
}
编辑2
DROP掉的for循环,以及 - !只是交换引用,左不过是在执行两次功能
EDIT 2 Droped the for loops as well - just exchanging references, nothing left but a function being executed twice !
推荐答案
您正在编译整个元素(包括指令的模板,它已被编译添加了一部分):
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);
这篇关于为什么这个函数执行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!