从控制器调用service.js文件

时间:2016-01-04 22:38:24

标签: angularjs angularjs-scope angularjs-service angularjs-controller angularjs-module

我有一个需要从控制器调用的服务文件。有人可以告诉代码应该进入控制器以获取此服务文件。谢谢。

这是我的服务文件代码

"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
                   }
           ];

       });

这是我的控制器代码

"use strict"; 

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




    }]);

这是我的HTML代码

<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>

1 个答案:

答案 0 :(得分:1)

"use strict"; 

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

     $scope.trucks = trucksService.getTrucks();

}]);