angular.js按月过滤

时间:2015-08-23 18:43:34

标签: javascript angularjs

我正在尝试制作一个过滤器,它只显示1月份某个月的json条目。但是,我遇到了麻烦。我尝试为Jan和Feb设置变量,然后将输入设置为大于Jan中的第一个日期并且小于2月的第一个日期,但这没有奏效。任何帮助将不胜感激。

这是我的HTML:

<div ng-app="myApp" ng-controller="Catalog">
<div class="bg" ng-repeat="book in books">
    <div ng-show=" book.doc.date | mydate" >
    <div class="date">{{book.doc.date}}</div>
    <div class="title">{{book.doc.title}}</div>
    <div class="quote">{{book.doc.quote}}</div>
    <div class="attribution">-{{book.doc.attribution}}</div>
    <div class="textt">{{book.doc.text}}</div>
  <div style="height:10px"></div>      
  </div>
  </div>

  <div class="bg" ng-repeat="book in books ">
  <div ng-click="showInfo = !showInfo" ng-show=" book.doc.date | January">
  <div class="date">{{book.doc.date}}</div>
  <div class="title">{{book.doc.title}}</div>
        <div class="quote"  ng-show="showInfo">{{book.doc.quote}}</div>
            <div class="attribution" ng-show="showInfo">-    {{book.doc.attribution}}</div>
                <div class="textt" ng-show="showInfo">{{book.doc.text}}       </div>    
<div style="height:10px"></div>    
</div>
</div>
</div>

和我的JS:

var myApplication = angular.module('myApp', ['ngColorThis']);
myApplication.controller("Catalog", function ($scope) {
$scope.books = books;
$scope.showInfo = false;
})

.filter('mydate', function() {
return function(input) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0, so always add + 1
var yyyy = today.getFullYear();
if (dd < 10) {
  dd = '0' + dd
}
if (mm < 10) {
  mm = '0' + mm
}
today = mm + '/' + dd;
return (input == today)
}
})

.filter('past', function() {
return function(input) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0, so always add + 1
var yyyy = today.getFullYear();
if (dd < 10) {
  dd = '0' + dd
}
if (mm < 10) {
  mm = '0' + mm
}
today = mm + '/' + dd;
return (input)
}
})

.filter('January', function() {
return function(input) {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0, so always add + 1
var yyyy = today.getFullYear();
if (dd < 10) {
  dd = '0' + dd
}
if (mm < 10) {
  mm = '0' + mm
}
today = mm + '/' + dd;
var jan = 00 + "/" +00;
var feb = 01 + "/" + 00;
return (input > jan && input < feb)
}
});

此处还有我项目的完整plunker

2 个答案:

答案 0 :(得分:1)

使January过滤器正常工作的最简单方法如下:

.filter('January', function() {
  return function(input) {
    return input.slice(0,2) === '01';
  }
});

如您所见,所需要的只是前两位的简单比较。

当然,您也可以在表达式中简单地内联:

ng-show="book.doc.date.indexOf('01') == 0"

更好的是,使用ng-if代替ng-show,或在显示所有需要的项目之前过滤数组。

答案 1 :(得分:1)

您应该在过滤器表达式

中使用filter
<div ng-show=" book.doc.date | filter: mydate" >

<div ng-click="showInfo = !showInfo" ng-show=" book.doc.date | filter: January">