Linking one controller to another to call service

2019-01-09 20:04发布

问题:

I have two templates with respective controllers and service files. One template's(fleetListTemplate) controller(fleetListController) loads data from its service file(fleetService) and displays in its view(fleetListTemplate).

When this happens, and I click on one of the loaded data from fleetService, I should link fleetListController to fleetSummaryController to get data from its service file (fleetSummaryService) and display in fleetSummaryTemplate view.

Can someone please help me with the coding? Thank you.

The following are the respective modules, templates, controllers and service files.

fleetListModule

"use strict";

angular.module("fleetListModule", []);

fleetListTemplate

<div class="panel1 panel-primary">
    <div class="panel-heading" align="center">TRUCKS</div>
    <table class="table table-bordered table-condensed table-striped">

        <tr>
            <th>TruckID</th>
            <th>Status</th>
            <th>Dest.</th>
            <th>Alerts</th>
        </tr>
        <tr ng-repeat="truck in trucks" ng-click="summaryData()">
            <td>{{truck.truckID}}</td>
            <td>{{truck.status}}</td>
            <td>{{truck.destination}}</td>
            <td>{{truck.alerts}}</td>
        </tr>

    </table>
</div>

fleetListController

"use strict";

angular.module("fleetListModule").controller("fleetListController",
    ['$scope', 'fleetsService', 
        function ($scope, fleetsService) {

            $scope.trucks = fleetsService.getTrucks();


            $scope.summaryData = function () {
                $rootScope.$broadcast('obtainSummary');
            }

        }]);

fleetSummaryModule

"use strict";

angular.module("fleetSummaryModule", []);

fleetSummaryTemplate

<div class="panel2 panel-primary">
    <div class="panel-heading">Summary</div>
    <table class="table table-bordered table-condensed table-striped">

        <tr ng-repeat="summary in truckSummary">
            <td>Truck ID: {{summary.truckID}}</td>
            <td>Trailer ID: {{summary.trailerID}}</td>
            <td>Driver ID: {{summary.driverID}}</td>
            <td>Truck Number: {{summary.truckNumber}}</td>
            <td>Trailer Number: {{summary.trailerNumber}}</td>
            <td>Insurance Due Date: {{summary.insuranceDueDate}}</td>
            <td>Maintenance Due Date: {{summary.maintenanceDueDate}}</td>
        </tr>

    </table>
</div>

fleetSummaryController

"use strict";

angular.module("fleetSummaryModule").controller("fleetSummaryController",
    ['$scope', 'fleetSummaryService',
        function ($scope, fleetSummaryService) {
        $scope.$on('obtainSummary', function (event, args) {

            $scope.truckSummary = fleetSummaryService.getSummary();
        })

        }]);

fleetSummaryService

"use strict";

angular.module("fleetSummaryModule").service("fleetSummaryService",

       function () {
           this.getSummary = function () {
               return summary;
           };
           this.getSummary = function (truckID) {
               for (var i = 0, len = truckSummary.length; i < len; i++) {
                   if (truckSummary[i].truckID === parseInt(truckID)) {
                       return truckSummary[i];
                   }
               }
               return {};
           };
           var truckSummary = [
               {
                   truckID: 1,
                   trailerID: '123',
                   driverID: 'Alex123',
                   truckNumber: 'hyt 583',
                   trailerNumber: 'xyz213',
                   insuranceDueDate: '25-12-2015',
                   maintenanceDueDate: '31-12-2015'

               },
                   {
                       truckID: 2,
                       trailerID: '456',
                       driverID: 'Alex123',
                       truckNumber: 'hyt 583',
                       trailerNumber: 'xyz213',
                       insuranceDueDate: '25-12-2015',
                       maintenanceDueDate: '31-12-2015'

                   },
                   {
                       truckID: 3,
                       trailerID: '789',
                       driverID: 'Alex123',
                       truckNumber: 'hyt 583',
                       trailerNumber: 'xyz213',
                       insuranceDueDate: '25-12-2015',
                       maintenanceDueDate: '31-12-2015'
                    }
           ];

       });

回答1:

This simple example show to you how to share data between 2 controllers "in one app" using common service.

angular.module("app", []);

        ///controller1
        angular.module("app").controller("controller1", function ($scope, service) {
            $scope.lists = [
                { name: "maher" },
                { name: "Gaurav Ram" },
                { name: "Shaun Scovil" }
            ];

            $scope.send = function () {
                service.set("lists", $scope.lists); //set(key, value)
                $scope.lists = []; //optional
            }

        });

        ///controller2
        angular.module("app").controller("controller2", function ($scope, service) {
            $scope.lists = [];

            //get data from broadcast on the root
            service.get("lists"); // get(key)

            //set data
            $scope.resive = function () {
                if (angular.isUndefined($scope.broadcast)) {
                    $scope.alert = "No data to resive!";
                } else {
                    $scope.alert = null;
                    $scope.lists = $scope.broadcast;
                }
            }
        });

        ///service
        angular.module("app").service("service", function ($rootScope) {
            this.set = function (key, value) {
                $rootScope.$broadcast(key, value);
            }

            this.get = function (key) {
                $rootScope.$on(key, function (event, data) {
                    $rootScope.broadcast = data;
                });
            }
        });
<!doctype html>
<html ng-app="app">
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>

    <div ng-controller="controller1" class="col-md-6 col-sm-6 col-xs-6">
        <div class="page-header">
            <h1>controller 1</h1>
        </div>

        <button ng-click="send()" class="btn btn-primary">Send</button>
        <div class="clearfix"></div>
        <br/>
        <div class="alert alert-info" ng-if="lists.length == 0">Data <b>sent</b> to controller 2, click Resive button to get data</div>
        <ul class="list-group">
            <li ng-repeat="list in lists" class="list-group-item" ng-bind="list.name"></li>
        </ul>
    </div>

    <div ng-controller="controller2" class="col-md-6 col-sm-6 col-xs-6">
        <div class="page-header">
            <h1>controller 2</h1>
        </div>

        <button ng-click="resive()" class="btn btn-success">Resive</button>
        <div class="clearfix"></div>
        <br />
        <div class="alert alert-info" ng-bind="alert" ng-if="alert"></div>
        <ul class="list-group">
            <li ng-repeat="list in lists" class="list-group-item" ng-bind="list.name"></li>
        </ul>

    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</body>
</html>