Optimise ng-bind directive in angularjs

混江龙づ霸主 提交于 2019-11-29 18:16:52

I would suggest to use lodash https://lodash.com library to append the time diffrence in each object instead using directive to do that. so each time you get data from query use _.each to do the same operation and insert var realtime.

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

app.controller('list', function($scope,$window) {

  $scope.time = [
    {"game":"Halo","now":1554805270181,"time":1554794475267},
    {"game":"CODuty","now":1554805270181,"time":1554802957031},
    {"game":"WOF","now":1554805270181,"time":1554732154093},
    {"game":"WarCraft","now":1554805270181,"time":1554803456875},
    {"game":"POP","now":1554805270181,"time":1554803456275},
    {"game":"RedBulls","now":1554805270181,"time":1554800620012},
    {"game":"Eragon","now":1554805270181,"time":1554433320072}
  ];

  _.each($scope.time, function(obj, index){   
      var startDate = new Date(obj.time);
      var endDate = new Date(obj.now);
      var milisecondsDiff = endDate - startDate;
      var final = Math.floor(milisecondsDiff / (1000 * 60 * 60)).toLocaleString(undefined, {
        minimumIntegerDigits: 2
      }) + ":" + (Math.floor(milisecondsDiff / (1000 * 60)) % 60).toLocaleString(undefined, {
        minimumIntegerDigits: 2
      }) + ":" + (Math.floor(milisecondsDiff / 1000) % 60).toLocaleString(undefined, {
        minimumIntegerDigits: 2
      });
      var defaulttime = '00:00:00';
      if (final == '-01:-01:-01') {
        obj.realtime = defaulttime;
      } else {
        obj.realtime = final;
      }
  });
    
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>

<div ng-app="angularapp">
<div ng-controller="list" >
<div ng-repeat="timer in time">
<h5>{{timer.game}}</h5><hr/>
Milliseconds to H:M:S for {{timer.game}} <p style="display:inline-block;">{{timer.realtime}}</p><br>
</div>
</div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!