代码之家  ›  专栏  ›  技术社区  ›  r3plica

角度控制对象列表在同一视图上的可见性

  •  0
  • r3plica  · 技术社区  · 6 年前

    在AngularJS中,如果有两个列表,第二个列表依赖于第一个列表的值,那么它将自动更新。可以这样做:

    function toDoCtrl($scope) {  
      $scope.questions = [
        {
          active: true,
          text: "Question 1",
          answers: [
            {
              text: "Answer 1"
            },
            {
              text: "Answer 1"
            },
            {
              text: "Answer 3"
            }
          ]
        },
        {
          active: true,
          text: "Question 2",
          answers: [
            {
              text: "Answer 4"
            },
            {
              text: "Answer 5"
            },
            {
              text: "Answer 6"
            }
          ]
        }
      ];
      $scope.setActive = function(question) {
        question.active = !question.active;
      };
    }
    

    它在代码笔上:

    https://codepen.io/r3plica/pen/dQzbvX?editors=1010#0

    现在,我想用 角度6 但似乎不起作用…

    以下是同样的事情,使用角度:

    https://stackblitz.com/edit/angular-qkxuly

    有人能帮我把它弄好吗?还是给我个方向?


    我尝试使用此链接自己执行此操作:

    https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html

    但当我更新Stackblitz时,它没有起作用:(

    https://stackblitz.com/edit/angular-jya414

    我要试试别的,因为这不管用。我很惊讶没有人发布任何可能的解决方案……我认为这是一件很平常的事情。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Alex K    6 年前

    这个 filter 管子成角了。从 https://angular.io/guide/pipes 以下内容:

    Angular不提供用于筛选或排序列表的管道。熟悉AngularJS的开发人员将其称为filter和orderby。在角度上没有等价物。

    他们建议在组件逻辑中过滤列表项:

    Angular团队和许多经验丰富的Angular开发人员强烈建议将过滤和排序逻辑移入组件本身。组件可以公开过滤的英雄或排序的英雄属性,并控制何时和多久执行支持逻辑。任何你将放在管道中并在应用程序间共享的功能都可以写在过滤/排序服务中并注入到组件中。

    因此,对于您的示例,您可以这样做:

    questions: Question[] = [
      {
        active: true,
        text: "Question 1",
        answers: [
          {
            text: "Answer 1"
          },
          {
            text: "Answer 1"
          },
          {
            text: "Answer 3"
          }
        ]
      },
      {
        active: true,
        text: "Question 2",
        answers: [
          {
            text: "Answer 4"
          },
          {
            text: "Answer 5"
          },
          {
            text: "Answer 6"
          }
        ]
      }
    ]
    activeQuestions = this.questions.filter(q => q.active);
    
    setActive(question: Question): void {
      question.active = !question.active;
      this.activeQuestions = this.questions.filter(q => q.active);
    }
    

    在模板中:

    <div *ngFor="let question of activeQuestions">
    
        2
  •  0
  •   Amir Fawzy    6 年前

    试试这个

    <ng-container *ngFor="let question of questions">
      <div *ngIf="question.active">
        <ul>
          <li *ngFor="let answer of question.answers">{{ answer.text }}</li>
        </ul>
      </div>
    </ng-container>
    

    当我们添加 ngFor 迭代 array 然后我们限制输出使用 ngIf 如果 true 继续并重复 question.answers …这是你的 stackblitz 编辑后。

    有多种方法可以做到这一点 数组 filter 或在 dom 使用 NGIF NGOF 选择适合你需要的。