2016-02-11 4 views
0

В лучших практиках я пытаюсь объединить свои глобальные функции в многоразовые фабричные сервисы. В приведенном ниже коде я пытаюсь запустить функцию, которая примет строковое значение «Qprogress» в моих данных JSON, запустит некоторую математику и добавит вывод к элементу с классом «percent». Как я могу это сделать?Угловая служба подачи JS

HTML:

<table class="table table-striped table-condensed" ng-controller = "clientStatus"> 
     <thead> 
     <tr> 
      <th>Client</th> 
      <th>Status</th> 
      <th>Icon</th> 
     </tr> 
     </thead> 
     <tbody> 
     <tr ng-repeat="item in clients"> 
      <td><a href="#/details/{{clients.indexOf(item)}}" title="Link to {{item.FirstName}} {{item.LastName}}" class="oly-open">{{item.FirstName}} {{item.LastName}}</a></td> 
      <td ng-hide="item.Progress == 'In Progress'" ng-class="{ 'status-success': item.Progress == 'Questionnaire Completed', 'status-error': item.Progress == 'Unsent'}">{{item.Progress}}</td> 
      <td ng-if="item.Progress == 'In Progress'" class="status-info percent" ng-init="progressCalc(item)"></td> 
      <td width="10%"><a href="#/reports/" title{{$index + 1}}="Reports" ng-show="{{item.Progress == 'Questionnaire Completed'}}"><span class="stat-icon-report"></span></a> <a href="#/sends/{{$index + 1}}" title="Alert" ng-show="{{item.Progress == 'Unsent'}}"><span class="stat-icon-bullhorn"></span></a> <a href="#/progress/{{$index + 1}}" title="In Progress" ng-show="{{item.Progress == 'In Progress'}}"><span class="stat-icon-phone"></span></a></td> 
     </tr> 
     </tbody> 
    </table> 

AngularJS:

var myApp = angular.module('myApp', []); 

    myApp.factory('progressCalc', function() { 
     angular.forEach(function(item) { 
     var m = 0.26664; 
     var s = 0.26664; 
     var i = 0.694375; 
     var t = item.Qprogress; 
     t = t.replace(/m/g, ''); 
     t = t.replace(/s/g, ''); 
     t = t.replace(/i/g, ''); 
     var ta = t.split("/"); 
     var tTotal = (ta[0] * m) + (ta[1] * s) + (ta[2] * i); 
     Math.round(tTotal); 
     (tTotal + '%').append('.percent'); 
     }); 
    }); 
    myApp.controller('clientStatus', ['$scope', '$http', function($scope, $http) { 
     $http.get('assets/js/lib/angular/clientList.json').success(function(data) { 
     $scope.clients = data; 

     }); 
    }]); 

сниппетов из JSON:

{ 
     "FirstName": "Jane", 
     "LastName": "Greenberg", 
     "Company": "Nike", 
     "CompanyId": "2345672", 
     "ClientId": "EFTGE6", 
     "Title": "CIO", 
     "Phone": "555-555-5555", 
     "ClientSystemStatus": "Active", 
     "CreationDate": "06/12/2015, 9:12:27 am", 
     "Progress": "In Progress", 
     "Qprogress": "m125/s108/i0", 
     "Email": "[email protected]" 
    } 

Я думал, что я мог бы обернуть свой код в функции, а затем нг-INIT на элемент, который я добавляю, но это не хочет работать.

ответ

0

Ваш factory должен возвращать повторно используемую деталь, которая будет использоваться в controller. Вычисления происходят в factory, а контроллер только называет это, а переданный в DOM (в вашем случае он должен быть лучше каталога).

//we define the factory, it will return on method 'doMath' 
myApp.factory('progressCalc', function() { 
return { 
    doMath: function(data) { 
     //here we will store the results 
     var values = []; 

     angular.forEach(function(data) { 
      var m = 0.26664; 
      var s = 0.26664; 
      var i = 0.694375; 
      var t = item.Qprogress; 
      t = t.replace(/m/g,''); 
      t = t.replace(/s/g,''); 
      t = t.replace(/i/g,''); 
      var ta = t.split("/"); 
      var tTotal = (ta[0] * m) + (ta[1] * s) + (ta[2] * i); 
      Math.round(tTotal); 

     values.push(tTotal + '%'); 

     }); 
     //here give the results back to controller 
      return values; 
     } 
    } 
}); 

//your controller 
myApp.controller('clientStatus', ['$scope', '$http', 'progressCalc', function($scope, $http, progressCalc) { 

    //...other stuff 

    $http.get('assets/js/lib/angular/clientList.json').success(function(data) { 

     //here we have the data 
     //and call progressCalc factory 
     $scope.clients = progressCalc.doMath(data); 

     //here you can do smth like 

     $scope.clients.forEach(function(item){ 
     item.append('.percent') 
     }); 
    }); 

}); 
+0

Это не работает, потому что замена параметра элемента с параметром data в функции get.success разрывает ссылку на мою переменную t. –

+0

это не решение для копирования-вставки, извините. Надеюсь, у вас есть идея - как и где делать вещи – shershen

0

Также в функции вам нужно будет внести некоторые изменения (см первый ответ), вероятно,

angular.forEach(function(data) { 

должен быть

angular.forEach(data, function(item) { 
... 
tTotal = Math.round(tTotal); 
...