Search code examples
angularjsangularjs-scopeangularjs-serviceangularjs-controllerangularjs-module

Calling service.js file from controller


I have a service file which needs to be called from the controller. Can someone please tell the code which should go in the controller to get this service file. Thank you.


This is my service file code

"use strict";

angular.module('jsFleet').service('trucksService',

       function () {
           this.getTrucks = function () {
               return trucks;
           };
           this.getTruck = function (truckID) {
               for (var i = 0, len = trucks.length; i < len; i++) {
                   if (trucks[i].truckID === parseInt(truckID)) {
                       return trucks[i];
                   }
               }
               return {};
           };
           var trucks = [
               {
                   truckID: 1,
                   status: Running,
                   destination: WPG,
                   alerts: Nothing
               },
                   {
                       truckID: 5,
                       status: Running,
                       destination: WPG,
                       alerts: Nothing
                   },
                   {
                       truckID: 2,
                       status: Running,
                       destination: WPG,
                       alerts: Nothing
                   },
                   {
                       truckID: 3,
                       status: Running,
                       destination: WPG,
                       alerts: Nothing
                   },
                   {
                       truckID: 4,
                       status: Running,
                       destination: WPG,
                       alerts: Nothing
                   }
           ];

       });

This is my controller code

"use strict"; 

angular.module("jsFleet").controller("jsFleetController",
    ['$scope', 'trucksService', function ($scope, trucksService) {




    }]);

This is my HTML code

<div class="panel panel-primary">
    <div class="panel-heading" align="center">TRUCKS</div>
        <table class="table table-bordered table-condensed table-striped">
             <tbody>
                <tr>
                    <th>TruckID</th>
                    <th>Status</th>
                    <th>Dest.</th>
                    <th>Alerts</th>
                </tr>
            <tr ng-repeat="row in trucks">
                <td>{{row.truckID}}</td>
                <td>{{row.status}}</td>
                <td>{{row.destination}}</td>
                <td>{{row.alerts}}</td>
            </tr>      
            </tbody>
        </table>
    </div>

Solution

  • "use strict"; 
    
    angular.module("jsFleet").controller("jsFleetController", 
      ['$scope', 'trucksService', function ($scope, trucksService) {
    
         $scope.trucks = trucksService.getTrucks();
    
    }]);