如何通过angularJS对象属性过滤 [英] How to filter by object property in angularJS
问题描述
我想在AngularJS将由特定属性的值筛选对象列表创建自定义过滤器。在这种情况下,我想用极属性(可能值积极的,中性,负)进行过滤。
I am trying to create a custom filter in AngularJS that will filter a list of objects by the values of a specific property. In this case, I want to filter by the "polarity" property(possible values of "Positive", "Neutral", "Negative").
这是我的工作code,无过滤器:
Here is my working code without the filter:
HTML:
<div class="total">
<h2 id="totalTitle"></h2>
<div>{{tweets.length}}</div>
<div id="totalPos">{{tweets.length|posFilter}}</div>
<div id="totalNeut">{{tweets.length|neutFilter}}</div>
<div id="totalNeg">{{tweets.length|negFilter}}</div>
</div>
这里是JSON格式的$ scope.tweets数组:
{{created_at: "Date", text: "tweet text", user:{name: "user name", screen_name: "user screen name", profile_image_url: "profile pic"}, retweet_count: "retweet count", polarity: "Positive"},
{created_at: "Date", text: "tweet text", user:{name: "user name", screen_name: "user screen name", profile_image_url: "profile pic"}, retweet_count: "retweet count", polarity: "Positive"},
{created_at: "Date", text: "tweet text", user:{name: "user name", screen_name: "user screen name", profile_image_url: "profile pic"}, retweet_count: "retweet count", polarity: "Positive"}}
最好的过滤器,我可以想出如下:
myAppModule.filter('posFilter', function(){
return function(tweets){
var polarity;
var posFilterArray = [];
angular.forEach(tweets, function(tweet){
polarity = tweet.polarity;
console.log(polarity);
if(polarity==='Positive'){
posFilterArray.push(tweet);
}
//console.log(polarity);
});
return posFilterArray;
};
});
这个方法返回一个空数组。没有任何事情是从的console.log(极性)语句打印。好像我不插入正确的参数来访问的对象属性极。
This method returns an empty array. And nothing is printed from the "console.log(polarity)" statement. It seems like I am not inserting the correct parameters to access the object property of "polarity."
任何想法?你的反应是很大的AP preciated。
Any ideas? Your response is greatly appreciated.
推荐答案
您只需要使用过滤器
过滤器(请参阅documentation ):
You simply have to use the filter
filter (see the documentation) :
<div id="totalPos">{{(tweets | filter:{polarity:'Positive'}).length}}</div>
<div id="totalNeut">{{(tweets | filter:{polarity:'Neutral'}).length}}</div>
<div id="totalNeg">{{(tweets | filter:{polarity:'Negative'}).length}}</div>
<大骨节病> 小提琴 骨节病>
这篇关于如何通过angularJS对象属性过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!