gpt4 book ai didi

javascript - 尝试在 AngularJS 中创建多重过滤器以按月份和年份 ID 过滤 JSON 数据

转载 作者:行者123 更新时间:2023-12-02 15:35:50 25 4
gpt4 key购买 nike

I have implemented AngularJS inside of the RoR framework. I am trying to create a multi-filter for the "ng-repeat" method to filter the JSON data by "month_id" and "year_id".

Currently I have the following code:

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." }
]

Controller:

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>

最佳答案

您的主要问题是您将数字与字符串进行比较并使用强比较运算符(请记住,“2”!== 2)。尝试在 currentDate.getFullYear() 和 currentDate.getMonth() 的过滤函数中使用 .toString() 方法。 或者您可以使用弱比较运算符 ==。

'2' == 2;  // true
'2' === 2; // false

执行此操作的 Angular 方法是编写自己的过滤器,并将该逻辑保留在 Controller 之外,这样就可以使该函数在应用程序中的任何位置都可重用。您可以在 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>

或者,在您的 Controller 中,您可以使用

$scope.sortedItems = $filter('thisMonth')($scope.items);

编辑:使用最后一种方法,您需要包含 $filter 作为依赖项。

关于javascript - 尝试在 AngularJS 中创建多重过滤器以按月份和年份 ID 过滤 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32952927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com