angular directives - Parent调用子隔离范围方法

时间:2016-01-07 13:36:54

标签: angularjs angularjs-directive angular-directive

在我的角度应用程序中,我有一个父指令,比如某种列表,包含许多子指令,比如项目。

我希望能够从父母的孩子那里调用某种方法。我事先知道我打电话给哪些孩子(通过输入项目列表的开头和结尾索引)。因此,我希望避免使用广播,因为我不想打电话给所有的孩子而只是选择少数几个。

孩子和父母都有自己独立的范围。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

尝试为您的父指令创建controllers。这对于您的孩子指令是可访问的,它是您的孩子指令的某种共享功能。然后,您可以注册一个函数,该函数可以向父控制器添加新函数,以便稍后执行。 让我给你一个简单的例子(也许它不适用于复制粘贴,它只是理论它应该是什么样子)

//parent directive's controller function
function ParentControllerFunction(){
    this.arrayOfChildFuncions = [];
}

//your child directive's link function
require: '^ParentControllerFunction'
link: function(scope, element, attr, ctrl){
    function myLittleFunction(){
       //hhere is your function that you can call
    }

    ctrl.arrayOfChildFuncions.push(myLittleFunction);
}

然后你可以根据你想要的那个来执行你的功能:

//executes the 3rd directive's function with the parameter 'hello'
arrayOfChildFuncions[3]('hello')

答案 1 :(得分:0)

您可以使用$ index从ng-repeat获取所需的指令,然后调用您的函数。 https://docs.angularjs.org/api/ng/directive/ngRepeat