Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - 如何按angularJS中的object属性进行过滤(How to filter by object property in 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.(我试图在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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You simply have to use the filter filter (see the documentation ) :(您只需使用filterfilter器(请参阅文档 ):)

<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(小提琴)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...