当我在html中格式化内容时,orderBy无法正常工作

时间:2017-06-17 21:45:52

标签: angularjs angularjs-orderby

<tr ng-repeat="data in PackagesData | orderBy : filterOption">
<td>{{data.name}}</td>
<td>{{data.packageType}}</td>
<td>{{convertDateFormatNormal(data.createdDate)}}</td>
</tr>

$scope.convertDateFormatNormal = function (date) {
        if(date){
            var dateFormatChange = new Date(date);
            var dateChanged = $filter('date')(dateFormatChange, "dd/MM/yyyy");
            return dateChanged;
        }
    };

filterOption in orderBy可以是任何名称,packageType或createdDate。但是名称和包类型按预期工作但是orderBy不适用于createdDate,因为我将日期格式从mm / dd / yyyy转换为dd / mm / yyyy以HTML格式显示,但它仍然只按mm / dd / yyyy顺序排序。

2 个答案:

答案 0 :(得分:1)

在角度js中,排序取决于范围变量的格式,而不是html中的打印格式。如果要使用dd / mm / yyyy格式对其进行排序,则必须格式化js文件中的日期&amp;通过'PackagesData'对象&amp;循环将它存储在像'modified_date'这样的键中。然后在html&amp;中输入{{modified_date}}用'modified_date'过滤它。 一旦我遇到同样的问题,但我就这样解决了。

答案 1 :(得分:1)

此示例基于... import { Font, AppLoading } from 'expo'; ... export default class App extends Component { async componentDidMount() { await Font.loadAsync(fontsStore); ... } ... } ,并注重完整日期的订单,如果我们有orderBy这样的话:

array

订单应为[ { createdDate: "2007-04-01T14:30" }, { createdDate: "2006-01-05T14:30" }, { createdDate: "2018-06-06T14:30" }, { createdDate: "2015-03-08T14:30" }, { createdDate: "2010-02-11T14:30" }, { createdDate: "2010-01-12T14:30" } ]; ,然后yyyy最后MM,我们必须创建自定义函数,将日期转换为一行,例如:

  

如果我们dd,则05/01/2006 => "dd/MM/yyyy"

记住结果应为20060105 => "yyyyMMdd而不是int

string
var app = angular.module("app", []);

app.controller("ctrl", ["$scope", "$filter", function($scope, $filter) {

  $scope.array = [{
      name: "John",
      packageType: 1,
      createdDate: "2007-04-01T14:30"
    },
    {
      name: "Mike",
      packageType: 2,
      createdDate: "2006-01-05T14:30"
    },
    {
      name: "Mike",
      packageType: 2,
      createdDate: "2018-06-06T14:30"
    },
    {
      name: "Mike",
      packageType: 2,
      createdDate: "2015-03-08T14:30"
    },
    {
      name: "Mike",
      packageType: 2,
      createdDate: "2010-02-11T14:30"
    },
    {
      name: "Mike",
      packageType: 2,
      createdDate: "2010-01-12T14:30"
    }
  ];

  $scope.orderByFullDate = function(object) {
    var x = object.createdDate.split('/');
    var y = "";
    if (angular.isDefined(x[1])) {
      y = x[2] + x[1] + x[0];
    }
    return parseInt(y); //result of '05/01/2006' is: 20060105
  };

  $scope.convertDateFormatNormal = function(object) {
    if (object) {
      var dateFormatChange = new Date(object.createdDate);
      var dateChanged = $filter('date')(dateFormatChange, "dd/MM/yyyy");
      object.createdDate = dateChanged;
    }
  };


}]);