小编典典

如何在angularJS中按对象属性过滤

javascript

我试图在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)”语句中不会打印任何内容。似乎我没有插入正确的参数来访问“极性”的对象属性。

有任何想法吗?非常感谢您的回复。


阅读 179

收藏
2020-05-01

共1个答案

小编典典

您只需要使用filter过滤器:

<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>

[Fiddle](http://jsfiddle.net/rAFjL/)

2020-05-01