问题
I have a question with some page about item search.
Let's say I have:
- A controller with result items to display
- A service that performs the search queries and interacts to the controller so it updates the result items to display
- 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