简体   繁体   中英

angularjs custom filter in ng-repeat

I am trying to return unique values from a JSON response via a custom filter.

data:

[
{
    "SHFUserID": "400",
    "AlertID": "12",
    "TickerID": "4512",
    "Ticker": "GOOG",
    "Active": "1",
    "Status": "2"
},
{
    "SHFUserID": "400",
    "AlertID": null,
    "TickerID": "4512",
    "Ticker": "GOOG",
    "Active": null,
    "Status": null
},
{
    "SHFUserID": "400",
    "AlertID": null,
    "TickerID": "10190",
    "Ticker": "IBM",
    "Active": null,
    "Status": null
}
]

filter:

.filter('uniqueTickers', function() {
return function(tickers) {
    var tags = {};
    angular.forEach(tickers, function(obj) {

      if(!(obj.Ticker in tags)){
        tags[obj.Ticker] = {id: obj.TickerID, name:obj.Ticker}

        if(!tags[obj.Ticker].pending){
          tags[obj.Ticker].pending = 0;
        }
        if(!tags[obj.Ticker].settled){
          tags[obj.Ticker].settled = 0;
        }
        if(!tags[obj.Ticker].order){
          tags[obj.Ticker].order = 3;
        }
      }
  if(obj.Status === "1"){
    tags[obj.Ticker].pending = 1;
    if(tags[obj.Ticker].order > 2){
      tags[obj.Ticker].order = 2;
    }
  }
  if(obj.Status === "2"){
    tags[obj.Ticker].settled = 1;
    if(tags[obj.Ticker].order > 1){
      tags[obj.Ticker].order = 1;
    }
  };
    });
return tags;
};

html:

 Search: <input ng-model="query">
  Sort by:
  <select ng-model="orderProp">
    <option value="name">Alphabetical</option>
    <option value="order">Alert Status</option>
  </select>
  <ul class="tickerList">
    <li ng-repeat="ticker in tickers | filter:query | orderBy:orderProp | uniqueTickers">
      <a href="#/ticker/{{ticker.id}}">{{ticker.name}}</a>
      <p>{{ticker}}</p>
    </li>
  </ul>

but the result looks like:

GOOG
{"id":"4512","name":"GOOG","pending":0,"settled":0,"order":3}

IBM
{"id":"10190","name":"IBM","pending":0,"settled":0,"order":3}

instead of:

GOOG
{"id":"4512","name":"GOOG","pending":0,"settled":1,"order":1}

IBM
{"id":"10190","name":"IBM","pending":0,"settled":0,"order":3}

The goal is to keep the result set unique but set "pending" or "settled" to true if any of the records for that ticker are pending or settled.

After some discussion, the answer was to avoid overwiting existing data by adding a check around the first section of logic like this:

if(!(obj.Ticker in tags)){
    tags[obj.Ticker] = {id: obj.TickerID, name:obj.Ticker};

    if(!tags[obj.Ticker].pending){
      tags[obj.Ticker].pending = 0;
    }
    if(!tags[obj.Ticker].settled){
      tags[obj.Ticker].settled = 0;
    }
    if(!tags[obj.Ticker].order){
      tags[obj.Ticker].order = 3;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM