I am trying to create a custom filter in AngularJS that will filter a list of objects by the values of a specific property.(我试图在AngularJS中创建一个自定义过滤器,它将按特定属性的值过滤对象列表。)
In this case, I want to filter by the "polarity" property(possible values of "Positive", "Neutral", "Negative").(在这种情况下,我想过滤“极性”属性(可能的值为“正”,“中性”,“否定”)。)
Here is my working code without the filter:(这是我没有过滤器的工作代码:)
HTML:(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>
Here is the "$scope.tweets" array in JSON format:(这是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"}}
The best filter I could come up with as follows:(我能想出的最好的过滤器如下:)
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;
};
});
This method returns an empty array.(此方法返回一个空数组。) And nothing is printed from the "console.log(polarity)" statement.(并且没有从“console.log(极性)”声明中打印出任何内容。) It seems like I am not inserting the correct parameters to access the object property of "polarity."(看来我没有插入正确的参数来访问“极性”的对象属性。)
Any ideas?(有任何想法吗?) Your response is greatly appreciated.(非常感谢您的回复。)
ask by sh3nan1gans translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…