angular 指令 - Parent 调用 children 独立作用域方法

angular directives - Parent calls children isolated scope method

在我的 angular 应用程序中,我有一个 parent 指令,比如某种列表,其中包含许多 child 指令,比如项目。

我希望能够从 parent 调用 children 上的某个方法。我事先知道 children 我要调用什么(通过输入项目列表的开始和结束索引)。因此,我希望避免使用广播,因为我不想呼叫所有 children,而只是选定的几个。

children 和 parent 都有自己独立的作用域。

我怎样才能做到这一点?

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

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

//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')