Angular 1.5,从父控制器中调用组件中的函数 [英] Angular 1.5, Calling a function in a component from Parent controller

查看:79
本文介绍了Angular 1.5,从父控制器中调用组件中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 1.5组件可以轻松地从该组件创建对父级的调用.有没有办法可以从父级控制器的函数中调用组件中的函数?

Angular 1.5 components easily allow creating a call back to the parent from the component. Is there a way i can call a function in a component from a function in parent's controller ?

可以说我的组件称为任务运行器,而下面是父容器中该组件的HTML.

Lets say my component is called task-runner and below is the HTML for it in the parent container.

<task-runner taskcategogyid=5></task-runner>

 <button type="button" ng-click="doSomethingInParent()">ParentToChildButton</button>

在这里此处.我希望当单击ParentToChildButton时,函数doSomethingInParent()调用组件中的remotefunc.

The plunkr is here. I want that when ParentToChildButton is clicked, the function doSomethingInParent() calls the remotefunc in component.

推荐答案

几种不同的方式:

  1. 将具有双向绑定(scope:{myattr:'='})的对象作为属性传递给task-item-header指令,然后该指令可以向父控制器添加函数以供调用.
  2. 设置一个属性,该属性具有单向绑定(scope:{myattr:'@'}),然后将attrs.$observe更改为触发操作,或者设置为双向绑定(scope:{myattr:'='}),然后将$scope.$watch更改为它可以触发操作.
  3. 使该指令引发一个事件(scope:{raiseLoaded:'&onLoaded'}),该事件传递一个表示远程控制对象的对象,该对象上带有触发所需动作的方法.要引发该事件,您可以在指令中调用类似raiseLoaded({remoteControl: remoteControlObj})的内容,然后侦听该事件,并使用<task-item-header on-loaded="setRemote(remoteControl)">,前提是您的父控制器上有一个setRemote()方法.
  1. Pass an object as an attribute with two-way binding (scope:{myattr:'='}) to the task-item-header directive which the directive could then add a function to for the parent controller to call.
  2. Set an attribute that has either one-way binding (scope:{myattr:'@'}) on it and then attrs.$observe changes to it to trigger the action, or two-way binding (scope:{myattr:'='}) and then $scope.$watch changes to it to trigger the action.
  3. Have the directive raise an event (scope:{raiseLoaded:'&onLoaded'}) that passes an object that represents a remote control object with a method on it that triggers the action you want. To raise the event, you'd call something like raiseLoaded({remoteControl: remoteControlObj}) within the directive, and then to listen to the event, you'd use <task-item-header on-loaded="setRemote(remoteControl)"> assuming you have a setRemote() method on your parent controller.

更新我刚刚意识到您的问题是使用AngularJS的较新版本,因此我不确定我的答案是否仍然适用.我暂时将其保留在此处,但是如果您发现它没有帮助,可以将其删除.

Update I just realized your question was for a newer version of AngularJS, so I'm not sure if my answer still applies. I'll leave it here for now, but if you find it is not helpful I can delete it.

这篇关于Angular 1.5,从父控制器中调用组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆