Angular JS:使用ng重复计算每行两次之间的差

Angular JS: Calculate Difference between two times for each row using ng-repeat

本文关键字:两次 之间 使用 JS ng 计算 Angular      更新时间:2023-09-26

我是AngularJS的新手。我只是想减去两列之间的时间,并使用ng repeat将结果保存到每行的第三列
预期输出:

9:00   10:30   90(in minutes)

HTML:

<table id="t1" style="border:none;">
    <tr><th>Start</th><th>Stop</th><th>Downtime(In Min)</th><th>Reason</th></tr>
    <tr ng-repeat="item in invoice.items">
    <td><input type="text" ng-model="item.start"></td>
    <td><input  type="text" ng-model="item.stop" ng-blur="diff()" ></td>
    <td><input  type="text" ng-bind="item.down" ></td>
    <td style="border:none;"><a href ng-click="remove(item)">X</a></td>
    </tr>
    <tr style="border:none;">
    <td style="border:none;"><a href ng-click="add()">+</a></td>
  </tr>
    </table>

AngularJS:

var mapp = angular.module('MyApp',[]);
mapp.controller('myCtrl',function($scope,$http){
 $scope.diff=function(){
                $scope.item.down=$scope.item.stop-$scope.item.start }
});

我无法将ng模型值从ng重复获取到控制器中。每当我添加行时,应该调用该函数。请帮帮我。提前谢谢。

您可以尝试以下操作:

注意: 此答案基于时间以24小时格式接受的假设

JSFiddle

function testCtrl($scope) {
  $scope.diff = "";
  $scope.$watch("startTime", function(newValue, oldValue) {
    $scope.diff = computeDiff(newValue, $scope.endTime);
  });
  $scope.$watch("endTime", function(newValue, oldValue) {
    $scope.diff = computeDiff($scope.startTime, newValue);
  });
  function computeDiff(startTime, endTime) {
    if (startTime && endTime) {
      var s_hr = startTime.split(":")[0] || 0;
      var s_min = startTime.split(":")[1] || 0;
      var e_hr = endTime.split(":")[0] || 0;
      var e_min = endTime.split(":")[1] || 0;
      return Math.abs((parseInt(e_hr) - parseInt(s_hr)) * 60) + Math.abs(parseInt(e_min) - parseInt(s_min))
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<div ng-app>
  <div ng-controller="testCtrl">
    <input type="text" ng-model="startTime">
    <input type="text" ng-model="endTime">
    <input type="text" ng-model="diff">
  </div>
</div>

以下是使用ng-blurng-repeat更新的Fiddle。

我很好奇为什么要使用ngBlur?相反,只需更改:

<td><input  type="text" ng-bind="item.down" ></td>

<td><input  type="text" ng-init="diff(item)">{{item.down}}</td>

在你的控制器中:

$scope.diff = function(item) {
    item.down = convertToDateTime(item.stop) - convertToDateTime(item.start);
}

这里,convertToDateTime是一个将输入字符串转换为日期(但不修改它!)并返回时间戳的函数。由于您没有指定字符串的格式,所以我将"从字符串中提取日期"部分留给您。