Rorschach
Rorschach

Reputation: 3802

ng-include a view with a Controller and with a variable from another Controller

Setting:

I have an angular app

I have a table of geographies. And it shows a names and descriptions.

What I Want:

I want a small view of geography's details to display if the user clicks on a given geography in the table. This view will contain many more bits of information. It will be controlled by a different controller than the table.

main.html:

<div ng-if="displaySingle" ng-controller="GeographyController">
    <div ng-include="'html/geography-detail.html'" ng-controller="GeographyDetailController"></div>
</div>


<tr ng-repeat="geography in geographies" ng-controller="GeographyController">
    <td ng-click="displaySingleFunction(geography.id)">{{geography.name}}</td>
    <td>{{geography.description}}</td>
</tr>

The issue here is that when the user clicks on a given row, I need to pass the id from the that row to the GeographyDetailController. But the controller for that row is in the GeographyController.

Question:

How do I make this line of code:

<div ng-include="'html/geography-detail.html'" ng-controller="GeographyDetailController"></div>

pass a single ID to the GeographyDetailController?

What I Have:

Clicking a given row can make my detail view appear and disappear, it just cannot send that view and its controller the ID that I need it to.

UPDATE 1

This works if I want to follow a link to the page, but I don't, I want to include this view into a larger view.

ui-sref="geographyDetail({uuid:geography.uuid})" 

Upvotes: 0

Views: 33

Answers (1)

Kenany
Kenany

Reputation: 562

From that I see, GeographyDetailController is a child controller of GeographyController . Then there are several ways to pass the parameter.

  1. You can use the $scope or $rootScope event. That is, when user click on the row, you emit event ($scope.$emit or $rootScope.$emit) from GeographyController , pass your id and call $scope.$on or $rootScope.$on in GeographyDetailController to get the id.

  2. Or you can do like this: when user click on the row, you add a new field in the $scope ($scope.myParam = id) inside the GeographyController and get it like this in the GeographyDetailController ($scope.$parent.myParam).

Personally, I advise you to use the second method.

Upvotes: 1

Related Questions