1

I have two controllers allocated to two views:

[ResultsView ng-controller="ResultsCtrl"] [SearchView ng-controller="SearchCtrl"]

The Search View has many complex filters/options and is filled in by the user, then he/she can press "Search" on SearchView and Results should be populated into a Grid.

Now I can send information between two either by a Service or by using $rootScope.$broadcast.


Heres the problem I've run into:

[ResultsView ng-controller="ResultsCtrl"][SearchView ng-controller="SearchCtrl"] [ResultsView ng-controller="ResultsCtrl"][SearchView ng-controller="SearchCtrl"] [ResultsView ng-controller="ResultsCtrl"][SearchView ng-controller="SearchCtrl"]

If I were to have multiple Result-Search sections on the same page, how can I ensure they each act independently from each other? Using the Service approach, the ResultsCtrl and SearchCtrl both have the defined service

.controller("searchCtrl", ["$scope", "$searchHttp", function ($scope, $searchHttp) {
.controller("resultsCtrl", ["$scope", "$searchHttp", function ($scope, $searchHttp) {

So I can't change how each instance of the controller behaves regarding the service. Soon as one SearchCtrl calls the service, it will modify every ResultsCtrl instance.

Likewise using broadcasts $rootScope.$broadcast("searchResults"... will be picked up by every ResultsCtrl instance.

So whats the best way around this? I want to reuse the Results and Search View code since its basically the same. But I need to render each pair independently on the same page a few times.

1 Answer 1

1

I think the HTML structure you need is something like this.

<!--First-->
<div ng-controller="SearchCtrl">
    <div ng-controller="ResultsCtrl">
    </div>
</div>

<!--Second-->
<div ng-controller="SearchCtrl">
    <div ng-controller="ResultsCtrl">
    </div>
</div>

This HTML structure would help you to use independently the search results one's parent SearchCtrl created in ResultsCtrl.

jsfiddle is here. I hope this would help you. :)

Sign up to request clarification or add additional context in comments.

2 Comments

I did not realise you could do this. Is this the right way to go around it? I mean the inner controllers don't know what scope variables are available in the parent ones until they actually execute.
I also think this is NOT the right way in all cases as you mentioned. But If you always use ResultsCtrl in SearchCtrl, this solution could work anway. If you insist some best practice, I would recommend to write the directive for rendering the results of SearchCtl instead of ResultsCtrl. The directives could get parameter from any parent controller. Enjoy!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.