我正在尝试在 AngularJS 中创建一个自定义过滤器,它将通过特定属性的值过滤对象列表。在这种情况下,我想按“极性”属性(“正”、“中性”、“负”的可能值)进行过滤。
这是我没有过滤器的工作代码:
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(polarity)”语句没有打印任何内容。似乎我没有插入正确的参数来访问“极性”的对象属性。
有任何想法吗?非常感谢您的回复。