Access parent controller methods from directive?

不问归期 提交于 2019-12-11 03:04:25

问题


I have a question with some page about item search.

Let's say I have:

  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.

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?

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?


回答1:


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:'&'
   }
}

Then on:

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

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

 ng-click="myFavoriteMethod()"

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.



来源:https://stackoverflow.com/questions/29776857/access-parent-controller-methods-from-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!