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

时间:2013-12-10 14:20:18

标签: javascript angularjs

我有一个树形结构。 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);
};

工厂正在找到正确的位置并添加节点。

将子项添加到包含现有子项的节点时,它会添加两个孩子并且我不明白为什么。

感谢。

修改 我可能会丢失has_children,但仍会产生相同的结果

updated JSBIN

会员链接功能

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 同时也调整了for循环 - 只是交换引用,没有剩下任何东西,只是执行了两次函数!

updated JSBIN

1 个答案:

答案 0 :(得分:3)

您正在编译整个元素(包括指令模板添加的已经编译的部分):

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

由于您的点击处理程序位于模板第二次编译模板,因此会添加第二组点击处理程序(等等)。

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

修复:而是使用它来编译您添加的新元素:

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

updated jsbin

相关问题