繁体   English   中英

根据父级ng-repeat过滤ng-repeat

[英]Filter an ng-repeat based on parent ng-repeat

现在crat头两个小时。 也许我累了,或者我不明白自己在做什么。 无论如何,我有很多博客文章。 看起来像这样:

[
  {
    'title': 'first post', 
    'tags': [
      { 'name': 'Tag 1', 'slug': 'tag-1' }
    ]
  },
  {
    'title': 'second post', 
    'tags': [
      { 'name': 'Tag 1', 'slug': 'tag-1' },
      { 'name': 'Tag 3', 'slug': 'tag-3' }
    ]
  },
  {
    'title': 'third post', 
    'tags': [
      { 'name': 'Tag 2', 'slug': 'tag-2' }
    ]
  }
]

还有一个包含我的标签的数组。

[
  {'title': 'Tag 1', 'slug':'tag-1'},
  {'title': 'Tag 2', 'slug':'tag-2'},
  {'title': 'Tag 3', 'slug':'tag-3'},
  {'title': 'Tag 4', 'slug':'tag-4'}
]

而且我正在像这样进行常规的角度ng-repeat,以显示所有博客文章标签:

<ul>
    <li ng-repeat="tag in blog.tags">
        <h3>{{ tag.title }}</h3>
    </li>
</ul>

现在,我想添加一个嵌套的转发器,该转发器仅显示来自包含当前标记的变量blog.posts博客blog.posts 像这样:

<ul ng-controller="BlogComponent as blog">
  <li ng-repeat="tag in blog.tags">
    <h3>{{ tag.title }}</h3>
    <ul>
      <li ng-repeat="post in blog.posts | filter: tag.slug IN post.tags">
        <span>{{ post.title }}</span>
      </li>
    </ul>
  </li>
</ul>

但是我似乎无法正常工作。 我认为应该很容易。 因为在我看来,这是一个非常简单的任务。 根据字符串和数组过滤掉不需要的结果。

想要/期望的输出:

<ul>
  <li>
    <h3>Tag 1</h3>
    <ul>
      <li>first post</li>
      <li>second post</li>
    </ul>
  </li>
  <li>
    <h3>Tag 2</h3>
    <ul>
      <li>third post</li>
    </ul>
  </li>
  <li>
    <h3>Tag 3</h3>
    <ul>
      <li>second post</li>
    </ul>
  </li>
</ul>

您可以制作自定义过滤器,而不使用“ filter:expression”。 您可以做的是创建一个过滤器,该过滤器将标签和帖子作为参数,并返回包含过滤项的数组。

myApp.filter('myFilter', function () {
    return function (posts, tag) {
        var newPosts = [];
          for (var i = 0; i < posts.length; i++) 
            for (var j = 0; j < post.tags.length; j++) 
             if (posts[i].tags[j].slug === tag.slug)
                newPosts.push(posts[i]);

        return newPosts;
    }
});

接着

  <li ng-repeat="post in blog.posts | myFilter: tag">
    <span>{{ post.title }}</span>
  </li>

使用内置功能,您可以这样进行:

<ul ng-controller="BlogComponent as blog">
  <li ng-repeat="tag in blog.tags">
    <h3>{{ tag.title }}</h3>
    <ul>
      <li ng-repeat="post in blog.posts | filter: {tags: {slug: tag.slug}}">
        <span>{{ post.title }}</span>
      </li>
    </ul>
  </li>
</ul>

看到它在这里工作: https : //plnkr.co/edit/pQZse1hUnnzyfneIlpMu?p=preview

过滤器的文档在这里: https : //docs.angularjs.org/api/ng/filter/filter

或者,如果您希望标签4由于没有匹配的帖子而被隐藏,则可以执行以下操作:

<div ng-controller="BlogComponent as blog">
  <div ng-repeat="tag in blog.tags">
    <div ng-repeat="post in blog.posts | filter: {tags: {slug: tag.slug}}">
      <h3 ng-if="$first">{{ tag.title }}</h3>
      <li>{{ post.title }}</li>
    </div>
  </div>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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