AngularJS:仅在最后一个选项卡上显示过滤的内容

AngularJS: Only shows filtered content on last tab

本文关键字:过滤 显示 最后一个 选项 AngularJS      更新时间:2023-09-26

我想在引导选项卡中使用角度过滤器。但是,只有最后一个选项卡向我显示过滤的内容,其余选项卡无响应("专业人员"选项卡)

标记

<div class="panel-body" ng-controller="exploreController as exploreCtrl"> 
    <ul class="nav nav-tabs" role="tablist" id="Tabs">
        <li role="presentation" ng-class="{active:exploreCtrl.isSelected(1)}" >
        <a aria-controls="project" role="tab" ng-click="exploreCtrl.select(1)">Projects</a></li>
        <li role="presentation" ng-class="{active:exploreCtrl.isSelected(2)}" >
        <a aria-controls="team" role="tab" ng-click="exploreCtrl.select(2)">Teams</a></li>
        <li role="presentation" ng-class="{active:exploreCtrl.isSelected(3)}" >
        <a aria-controls="prof" role="tab" ng-click="exploreCtrl.select(3)">Professionals</a></li> 
<div class="tab-content">
        <ul class="media-list tab-pane fade in active">
        <li ng-repeat = "proteam in exploreCtrl.proteams | filter:exploreCtrl.filtText">
<div class="panel-body">
    <div class="media-left media-middle">
</div>
    <div class="media-body">
        <h2 class="media-heading">{{proteam.name}} </h2>
        <span class="label label-danger">{{proteam.tag1}}</span>
        <p>{{proteam.description}}
        </p></div></div></li></ul></div>

爪哇语这是使用"setTab"和"checkTab"来确保ng-clickng-class获得正确值的地方。

var app = angular.module('exploresModule',[]);
app.controller('exploreController',function() {
     this.tab=1;
    this.filtText = '';
    var proteams = [
        {
            name:'Ziyad Alvi',
            tag1:'C++',
            type:'prof'
        },
        {
            name:'Organic Foods',
            tag1:'food',
            type:'project'
        },
        {
            name:'Telekenisis',
            tag1:'Xmen',
            type:'project'
        } ];
    this.proteams = proteams;
    this.select = function(setTab) {
        this.tab = setTab;
        if (setTab === 1) { this.filtText = 'project'; }
        if (setTab === 2) { this.filtText = 'team'; }
        if (setTab === 3) { this.filtText = 'prof'; }
        else this.filtText = '';
    };
    this.isSelected = function(checkTab) {
       return this.tab === checkTab;
    }
});

问题在于条件的编写方式

当数字不是 3 时,将始终运行最后一个else

所以当数字是一两个时...它到达if(setTab ===3),因为它不是else将值设置为空字符串

可以使用switch。或者总是return是一两个还是使用一系列if/else

  this.select = function(setTab) {
    this.tab = setTab;
    if (setTab === 1) {
      this.filtText = 'project';
    } else if (setTab === 2) {
      this.filtText = 'team';
    } else if (setTab === 3) {
      this.filtText = 'prof';
    } else {
      this.filtText = '';    
    };
  };

this.select = function(setTab) {
    this.tab = setTab;
    if (setTab === 1) { this.filtText = 'project'; return;}
    if (setTab === 2) { this.filtText = 'team'; return;}
    if (setTab === 3) { this.filtText = 'prof'; }
    else this.filtText = '';
};

演示