Angularjs过滤多级对象

时间:2015-08-31 22:23:54

标签: angularjs filter

我需要在angularjs中创建一个过滤器

我的数据看起来像这样:

[{
    name: 'account1', 
    accounts: [
      {
        name: 'account2', 
        accounts: []
      }, 
      {
        name: 'account3', 
        accounts: [
          {
            name: 'account4',
            accounts: []
          }
        ]
      }
    ]
 }]

如果我使用account4作为搜索文本,我需要过滤器返回完整对象。如果我使用account2等,或者只是前两个级别。

我已经搜遍过,但是找不到这样的东西,也不知道从哪里开始。

2 个答案:

答案 0 :(得分:1)

您需要create a custom filter来执行您要求的操作。控制器过滤器仅允许您提供表达式以包含或排除ng-repeat项目。

自定义过滤器允许您动态修改模型。您可以相应地拼接json对象。

当我回到电脑前时,我会提供一个例子。

答案 1 :(得分:1)

我终于明白了。这是我创建的自定义过滤器,以防其他人发现它有用:

.filter('accountsFilter', function() {

  return function(items, searchStr) {

    function filterAccounts(account, str) {

      //if account name matches
      if (account.name && account.name.toLowerCase().indexOf(str.toLowerCase()) > -1) {

        //expand parent account
        if (account.accounts && account.accounts.length > 0) account.expand = true;

        //return account
        return account;

      } else

      //account name doesnt match. check sub accounts
      if (account.accounts && account.accounts.length > 0) {

        //has accounts
        var fa = [];
        angular.forEach(account.accounts, function(act, k) {
          var a = filterAccounts(act, str);

          //if account was returned
          if (a !== false) {

            //add account to filtered accounts
            fa.push(act);
          }   
        });

        //add accounts to parent account
        account.accounts = fa;

        //if there are sub-accounts
        if (fa.length > 0) {

          //make sure account is expanded to show sub accounts
          if (account.accounts && account.accounts.length > 0) account.expand = true;

          //return account
          return account;

        //no sub accounts left
        } else {

          //check and return if main account matches
          return filterAccounts(account, str);
        }

      //no matches              
      } else {
        return false;
      }
    }

    //copy accounts list to prevent original being altered
    var accounts = angular.copy(items);
    var filtered = [];

    //loop through accounts list
    angular.forEach(accounts, function(account) {

      //check if current account matches
      var a = filterAccounts(account, searchStr.name);
      if (a) {

        //add to filtered list
        filtered.push(a);
      }
    });
    return filtered; 
  };
})