我在RoR框架中实现了AngularJS。我正在尝试为“ng-repeat”方法创建一个多过滤器,以按“month_id”和“year_id”过滤JSON数据。
目前我有以下代码:
JSON:
[
{ "date":"October 4, 2015",
"month_id":"10",
"year_id":"2015",
"name":"Chris",
"title":"Painter",
"company":"Freelancer",
"description":"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" },
{ "date":"October 3, 2015",
"month_id":"10",
"year_id":"2015",
"name":"Rebecca",
"title":"Writer",
"company":"John H. Hickenloop",
"description":"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" },
{ "date":"October 22, 2014",
"month_id":"10",
"year_id":"2014",
"name":"Josh",
"title":"Riddler",
"company":"Florida Museum",
"description":"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." }
]
控制器:
var myApp = angular.module('myApp', []);
myApp.controller("MyController", function MyController($scope, $http){
$http.get("/assets/data.json").success(function(data){
$scope.artists = data;
String.prototype.trunc = String.prototype.trunc ||
function(n){
// this will return a substring and
// if its larger than 'n' then truncate and append '...' to the string and return it.
// if its less than 'n' then return the 'string'
return this.length>n ? this.substr(0,n-1)+'...' : this;
};
$scope.myFilter = function(){
var currentDate = new Date;
return year_id === currentDate.getFullYear() && month_id === (currentDate.getMonth() + 1);
};
});
});
HTML:
<div ng-controller="MyController">
<ul>
<li ng-repeat="item in artists | filter: myFilter">
<h1>{{item.date}}</h1>
<p>{{ item.description.trunc(100) }}</p>
</li>
</ul>
</div>
答案 0 :(得分:2)
您的主要问题是您要将数字与字符串进行比较并使用强比较运算符(请记住,'2'!== 2)。尝试在currentDate.getFullYear()和currentDate.getMonth()的过滤器函数中使用.toString()方法。 或您可以使用弱比较运算符==。
'2' == 2; // true
'2' === 2; // false
Angular的做法是编写自己的过滤器并将该逻辑保留在控制器之外,这样,可以在应用程序的任何位置重复使用该函数。您可以在 https://docs.angularjs.org/guide/filter 找到有关编写自定义过滤器的文档。我会像这样接近这个:
myApp
.controller('MyController', function MyController($scope, $http) {
/** YOUR CODE HERE */
})
.filter('thisMonth', [function() {
return function(array) {
var results = [],
today = new Date(),
month = (today.getMonth() + 1).toString(),
year = today.getFullYear().toString();
angular.forEach(array, function(item, index) {
if (item.month_id === month && item.year_id === year) {
this.push(item);
}
}, results);
return results;
};
}]);
然后在你的ng-repeat中,你可以使用:
<ul>
<li ng-repeat="item in items|thisMonth">item.date</li>
</ul>
或者,在您的控制器中,您可以使用
$scope.sortedItems = $filter('thisMonth')($scope.items);
编辑:使用最后一种方法,您需要将$ filter作为依赖项。