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

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

问题描述

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

I have a question with some page about item search.

假设我有:

  1. 一个控制器,带有要显示的结果项
  2. 执行搜索查询并与控制器交互的服务,以便更新要显示的结果项
  3. 一个指令,它具有表单,其中包含搜索字段的所有输入.
  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.

我在 service 中创建了一个函数,它检查这个属性并将一个布尔值返回给 指令,它使用它和按钮上的 ng-show 来显示或隐藏

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-submit 在 控制器 上执行一些操作以调用 服务.像这样:

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>

所以现在我无法直接调用控制器方法.

So now I don't have access to call controller methods directly.

我应该如何处理这个问题?

How should I approach this?

推荐答案

我的回答与您的标题从指令访问父控制器方法"更具体一些.在您的指令中,您必须添加要共享的方法:

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-submit 按钮,它将表达式绑定到 onsubmit 事件(覆盖原始提交操作),这与 ng-click 不同,但您应该能够使用相同的模式.

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天全站免登陆