从指令访问父控制器的方法呢? [英] Access parent controller methods from directive?

本文介绍了从指令访问父控制器的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于商品搜索页面的一些问题。

I have a question with some page about item search.

让我们说我有:


  1. A 控制器结果项中显示

  2. A 服务执行搜索查询,所以它更新的结果项中显示
  3. 交互到控制器
  4. A 指令有在格式与搜索领域的所有输入。

  1. A controller with result items to display
  2. A service that performs the search queries and interacts to the controller so it updates the result items to display
  3. A directive which has the form with all the inputs of the search fields.

上的一颗扣子是一个查看更多物品按钮。它只应该如果我从查询接收响应告诉我,有更多的项目来查看图所示。

One of the buttons is a "View more items" button. It should only be shown if the response that I receive from a query tells me that there are more items to view.

我在服务哪些检查此属性,并返回一个布尔值里面做了一个函数在指令,其与NG-节目使用它上的按钮来显示或隐藏吧。

I made a function inside the service which checks this property and returns a boolean to the directive which uses it with a ng-show on the button to show or hide it.

问题是,我不知道如何在控制器此范围内进行互动。

The problem is that I don't know how to interact with the controller within this scope.

应该在指令拨打有一个服务方法并此方法应该与在控制器以某种方式进行交互?

Should the directive call one service method and this method should interact with the controller in some way?

在此之前,我包裹与表单标签指令(该指令的范围之内),然后我可以使用NG-提交执行控制器上的一些动作致电服务。像这样的:

Before this I was wrapping the directive with a form tag (outside the directive's scope) and then I could use the ng-submit to perform some action on the controller to call the service. Like this:

<form ng-submit="myController.submitSearch">
    <search-options-directive></search-options-directive>
    <button type="submit">
</form>

但现在我想要做的是把形式和内部的按钮

But now what I'm trying to do is to put the form and the buttons inside the

<search-options-directive></search-options-directive>

所以现在我没有访问调用的控制器方法直接。

我应该如何处理这个?

推荐答案

我的回答是一个比较具体到你的标题,从指令访问父控制器的方法。在您的指令,你必须添加你想要共享的方法:

My answer is a bit more specific to your title, "Access parent controller methods from directive." Within your directive you'll have to add the method that you want to share:

return {
   scope: {
     myFavoriteMethod:'&'
   }
}

然后在

<search-options-directive my-favorite-method="myMethodOnTheParentController"></search-options-directive>

在您的指令,您需要添加到您的HTML:

In your directive you'll need to add to your html:

 ng-click="myFavoriteMethod()"

但是,在您的例子中,你正在使用NG-提交按钮结合除权pression来onsubmit事件(覆盖原提交操作),这是从不同的NG-点击,但你应该能够使用相同的模式。

But in your example you're using a ng-submit button which binds the expression to onsubmit event (overriding the original submit action), which is different from ng-click, but you should be able to use the same pattern.

这篇关于从指令访问父控制器的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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