Belal Othman
Belal Othman

Reputation: 231

How can make the scope of $controller another controller scope

I have application with two modules 1- projects 2- documents

each project has many documents and when I select one project in the projects table I want to display its documents

for each module I made service.js and controller.js in the document controller.js there is function that get the suitable documents info form data base and fill it in document table

I am using this function to get data to my table

var documentCtrl = this;
documentCtrl.callServer = function callServer(projectId) {

        return documentsService.getDocuments(projectId).then(function(result){
                 documentCtrl.displayed = result.documents;
        });
    }

in the project table I want when select any project to get its documents and display it in document table

var projectCtrl = this;
projectCtrl.toggleSelection = function indexof(row){

  var documentController = $controller('documentsListController',{
      $scope : 'what I have to use here??' 
  });

  documentController.callServer(row.projectId);
}

when I call this function from projectCtrl the object documentCtrl.displayed is filled but the table stay empty

so I don't want to communicat between controllers all what I need is to call

callServer(projectId) {

        return documentsService.getDocuments(projectId).then(function(result){
                 documentCtrl.displayed = result.documents;
        });

and fill the documentCtrl.displayed with suitable value and display it in this table

<div id="documentsList" ng-controller="documentsListController as doc" >
<tr ng-repeat="row in doc.displayed">
        <td>{{row.documentId}}</td>
        <td>{{row.documentName}}</td>
        <td>{{row.documentExtension}}</td>
</tr>
</div>

Upvotes: 0

Views: 35

Answers (1)

Kunso Solutions
Kunso Solutions

Reputation: 7630

There are several possible ways to communicate between controllers.

  • services
  • events
  • watchers

The easiest one - Services. You have called documentsService you can save returned data to the variable inside that service. And it will be avaible across all controllers in which that service will be injected.

var documentCtrl = this;
documentCtrl.callServer = function callServer(projectId) {

    return documentsService.getDocuments(projectId).then(function(result){
             documentCtrl.displayed = result.documents;
             documentsService.documents = result.documets;
    });
}

And just inject service to second controller, once it will be called in first one, the result will be available in second too.

Upvotes: 1

Related Questions