【问题标题】:Angular filter list with switch (angular material)?带开关的角度过滤器列表(角度材料)?
【发布时间】:2017-11-23 15:45:04
【问题描述】:

所以我试图过滤我正在重复的列表,使用一个开关来过滤禁用的列表。 off 切换到常规列表。我使用棱角材料作为设计。 i ng-modeled showAll 绑定加载所有列表。我正在使用 asset.disabled 将禁用的那些放在重复中。所以我尝试使用 ctrl.infiniteAssets.disabled。不会工作。

import angular from 'angular'

import assetClassificationTemp       from './create-asset/partials/asset-classification-dialog.html';
import assetClassificationController from './create-asset/partials/classifications.controller.js';

import createAssetTemp               from './create-asset/create-asset.html';
import createAssetController         from './create-asset/create-asset.controller.js';
class AssetsController{
    constructor(siAsset, $mdDialog, $state, siAlertDialog,$timeout, $rootScope, $log, $q, helpDialog,$mdMedia, siTenant,toastIt,$filter, $scope){
        "ngInject";

        this.siAsset       = siAsset;
        this.$mdDialog     = $mdDialog;
        this.$state        = $state;
        this.siAlertDialog = siAlertDialog;
        this.$timeout      = $timeout;
        this.$rootScope    = $rootScope;
        this.$log          = $log;
        this.$q            = $q;
        this.helpDialog    = helpDialog;
        this.$mdMedia      = $mdMedia;
        this.siTenant      = siTenant;
        this.$filter       = $filter;
        this.$scope        = $scope;
        this.toastIt       = toastIt;


    }

    $onInit = () => {
        this.swtich           = false;
        this.hideToolbarTools = false;
        this.searchOpen       = false;
        this.componentList    = [];
        this.alertCount       = 0;
        this.loading          = false;
        this.disableTitle     = false;
        this.searchValue      = "";
        this.first            = true;
        this.settings         = {
                        printLayout: true,
                        showRuler: true,
                        showSpellingSuggestions: true,
                        presentationMode: 'edit'
        };

        this.global = this.$rootScope;

        this.$rootScope.$on('transform-toolbar-open', () => { 
           //hide toolbar controls on mobile
            
            if(this.$mdMedia('xs')){
                this.hideToolbarTools = true;        
            }else{
                this.hideToolbarTools = false
            }
        })

        this.$rootScope.$on('transform-toolbar-close', () => { 
            //show toolbar controls
            this.hideToolbarTools = false;
        })
        this.loadAssets()
    }


      loadAssets = () => {

        var self = this;
        self.infiniteAssets = {
            numLoaded_: 0,
            toLoad_: 0,
            items: [],
            pageNum:1,
            virtualIndex:0,

            getItemAtIndex: function (index) {
                this.virtualIndex=index;

                if (index > this.numLoaded_) {
                    this.fetchMoreItems_(index);
                    return null;
                }
                return this.items[index];
            },

            // Required.
            getLength: function () {
                if (this.virtualIndex > this.numLoaded_) {
                    return this.numLoaded_ ;
                }else{
                    return this.numLoaded_ + 5 ;
                }
            },

            fetchMoreItems_ : function (index) {
                if (this.toLoad_ < index) {
                    self.loading = true;
                    this.toLoad_ += 20;
                    self.siAsset.getAssets(this.pageNum++,20)
                        .then(angular.bind(this, function (assets) {
                            //this.objLength = assets.length;
                            if(! assets.statusCode){
                                this.items = this.items.concat(assets);
                                this.toLoad_ = this.items.length;
                                this.numLoaded_ = this.toLoad_;
                            }
                            self.loading = false;
                        }))
                }
            }
        };
    }
     refresh = () => {
        this.$state.reload();
    }

    sampleAction = (name, ev) => {
      this.$mdDialog.show(this.$mdDialog.alert()
        .title(name)
        .content('You triggered the "' + name + '" action')
        .ok('Great')
        .targetEvent(ev)
      );
    };

    loadDetail = (asset) => {
      this.$state.go('administration.assetdetail', {
        componentId: asset.id
      });
    }


    remoteSearch = (searchText) => {
        var deferred = this.$q.defer();
        this.siAsset.searchComponents(searchText, true)
            .then((data) =>{
                delete data.success;
                deferred.resolve(data);
            }, (err) => {
                deferred.reject(err);
            });
        return deferred.promise
    }

    createAsset = (ev) => {
        this.getClassificationList(ev);
    };

   deleteAsset = (asset) =>{
            let message = this.$filter('translate')('SI-MESSAGES.DEL-AST-MSG') + asset.name+'?';
            let title   = this.$filter('translate')('SUBHEADER.DEL-AST');
            let button  = this.$filter('translate')('BUTTON.DELETE');
            this.siAlertDialog.confirm(message,title,button)
            .then(() => {
                this.siAsset.deleteAsset(asset.id).then((data) =>{
                    this.toastIt.simple(this.$filter('translate')('SI-MESSAGES.ASSET-DEL-TOST'))
                    this.refresh()
                },(err) => {
                    this.siAlertDialog.warning(this.$filter('translate')('SI-MESSAGES.AST-CANT-DEL'));
                })
            })
        };
    showCreateAssetDialog = (ev) =>{
        this.$mdDialog.show({
                template:createAssetTemp,
                controller: createAssetController,
                controllerAs:'ctrl',
                event:ev,
                fullscreen: true,
                locals:{
                    classificationList : this.classificationList,
                    hasChilds: this.hasChilds,
                    selectedClassification : this.classification
                }
            })
            .then((resp) =>{
                if(resp !== 'closed'){
                    this.loadAssets();
                }
                
            }, () => {
                console.log("Error")
        });

    };

    //Get classifications past locations level (classifications of assets
    //i.e Parent Asset, Child Asset
     getLevel = () =>{
        var deferred = this.$q.defer();
        this.siTenant.getId().then((tenantID) =>{
                this.siTenant.getById(tenantID)
                    .then((_tenant) =>{
                        deferred.resolve(_tenant.locationsLevels);
                    },(err) =>{
                        deferred.reject(err);
                    })
            },(err) =>{
                deferred.reject(err);
            })

        return deferred.promise
    };

    showAssetTypesDialog = (ev) =>{
        this.$mdDialog.show({
            template:assetClassificationTemp,
            controller: assetClassificationController,
            controllerAs:'ctrl',
            fullscreen: true,
            locals:{
                classificationList : this.classificationList 
            }
        })
        .then((data) => {
            if(data !== 'closed'){
                this.classification = data;
                this.showCreateAssetDialog(ev);
            }
         
        },(err) => {
            console.log(err);
            console.log("Types Dialog Error!")
        });
    };

    getClassificationList = (ev) =>{
        this.getLevel().then((_locationLevel) => {
            this.siAsset.getClassifications()
                .then((data) => {
                    this.classificationList = [];
                    data.map((c) => {

                        if (c.level > _locationLevel) {
                            this.classificationList.push(c);
                        }
                    });


                    if(this.classificationList.length > 1){
                        this.hasChilds = true;
                        this.showAssetTypesDialog(ev);
                    }else{
                        this.hasChilds = false;
                        this.showCreateAssetDialog(ev);
                    }
                },(err) => {
                    this.siAlertDialog.error(err.message || 'Error fetching tenant location levels') ;
                });
        });
    };

     displayHelp = (ev) => {
       this.helpDialog.display(ev, this.$filter('translate')('ASSETS-TIPS.ASSET-TITLE'), this.$filter('translate')('ASSETS-TIPS.ASSETS-TIP-DESC'));
    }
    
}

export default AssetsController;
<md-toolbar class="md-primary">
  <md-progress-linear ng-show="$ctrl.loading || $ctrl.global.stateIsLoading" class="md-accent" md-mode="indeterminate"></md-progress-linear>
  <div class="md-toolbar-tools" layout-align="space-between center">
    <md-button ng-hide="$ctrl.hideToolbarTools" class="md-icon-button cssFade" aria-label="Toggle Menu" ng-click="$ctrl.global.toggle()" hide-gt-lg>
      <md-icon md-svg-icon="menu"></md-icon>
    </md-button>
    <span  ng-hide="$ctrl.hideToolbarTools"  class='cssFade'>
      <md-button aria-label="Go Back" ng-if="$ctrl.global.breadcrumbs" class="md-icon-button" ng-click="$ctrl.$rootScope.goBack()">
        <md-icon md-svg-icon="arrow-back"></md-icon>
      </md-button>

      <h1>{{$ctrl.global.topic}}</h1>
      <h1>{{$ctrl.global.subTopic | uppercase}}</h1>
    </span>
    <span flex ></span>
    <expand-search 
        search="$ctrl.searchValue" 
        remote-search="$ctrl.remoteSearch"
        on-selection="$ctrl.loadDetail"></expand-search>


    <si-tenant-toggle ng-hide='$ctrl.hideToolbarTools' is-dark='false'></si-tenant-toggle>

    
    <md-button aria-label="Help Button" ng-hide='$ctrl.hideToolbarTools' class='md-icon-button cssFade' ng-click='$ctrl.displayHelp($event)'>
      <md-icon md-svg-icon='help'></md-icon>
    </md-button>
  </div>
</md-toolbar>
   <div layout="row" layout-align="center end" class="resolvedSwitch">
          <md-switch ng-model='$ctrl.switch' ng-change="">
              {{'LABELS.SHOW-DISABLED' | translate}}
            </md-switch>
        </div>

<div>
  <md-content layout="column" class="full-height-content" layout-fill md-default-theme>
        <div layout="column" flex>
      <md-content class="full-height-content " >
        <div ng-if="$ctrl.infiniteAssets.getLength() <= 0 && !$ctrl.loading " layout layout-align="center center" layout-padding>
          <div class="notice " style=" text-align:center">
            <p>
              You have not defined any assets. To create a new asset, click the button on the bottom right of your screen 
              or <a class=" md-accent" ng-click="$ctrl.createAsset($event)"><span class="cursorPointer">click here</span></a>.
            </p>
          </div>
        </div>

        <md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && !$ctrl.switch">
          
          <md-list>
            <md-list-item  class="list-page" md-on-demand md-virtual-repeat='asset in $ctrl.infiniteAssets | assetsFilter:$ctrl.searchValue' ng-click="$ctrl.loadDetail(asset)">
              <span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
              <p>{{asset.name}} </p>                  
              <label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
                <md-chips>
                  <md-chip>{{'LABELS.DISABLED' | translate}}</md-chip>
                </md-chips>
              </label>
              <label><i>{{asset.status || 'UNKNOWN'}}</i></label>
                 <md-button aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
                       <md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
                  </md-button> 
              <md-divider></md-divider>
            </md-list-item>
          </md-list>
        </md-virtual-repeat-container>



      <md-virtual-repeat-container id="vertical-container" ng-show="$ctrl.infiniteAssets.getLength() > 0 && $ctrl.switch">
        
          <md-list>
            <md-list-item  class="list-page" md-on-demand md-virtual-repeat='asset in $ctrl.infiniteAssets | assetsFilter:$ctrl.searchValue' ng-click="$ctrl.loadDetail(asset)">
              <span class="search-status" style="border-left-color:{{asset.statusColor}};"></span>
              <p ng-if="asset.disabled">{{asset.name}} </p>                  
              <label hide-xs ng-if="asset.disabled" class="ng-animate-disabled">
                <md-chips>
                  <md-chip ng-if="asset.disabled">{{'LABELS.DISABLED' | translate}}</md-chip>
                </md-chips>
              </label>
              <label ng-if="asset.disabled"><i>{{asset.status || 'UNKNOWN'}}</i></label>
                 <md-button ng-if="asset.disabled" aria-label="Delete Asset" class="md-icon-button md-warn" layout-padding ng-click="$ctrl.deleteAsset(asset)">
                       <md-icon md-svg-icon="delete" class="modelTrashIcon"></md-icon>
                  </md-button> 
              <md-divider></md-divider>
            </md-list-item>
          </md-list>
        </md-virtual-repeat-container>



      </md-content>
    </div>
  </md-content>
</div>

<md-button aria-label="Create New Asset" class="md-fab md-fab-bottom-right" ng-click="$ctrl.createAsset()">
  <md-icon md-svg-icon="add"></md-icon>
</md-button>


<si-tenant-toggle-menu></si-tenant-toggle-menu>

【问题讨论】:

    标签: javascript html angularjs angularjs-ng-repeat angular-material


    【解决方案1】:

    您只需要使用ng-switch 模型并将每个项目的状态作为ng-if 中的条件。你可以直接在md-content中使用md-listmd-list-item。无需使用md-virtual-repeat-container,因为md-content 会在需要时添加滚动条。

    这里是 Javascript。

    angular.module('myApp',['ngMaterial'])
    .controller('TempController',function($scope){
     $scope.tempSwitch = true;
     $scope.data= [
     {name: "Asset 1", status: true},
     {name: "Asset 2", status: true},
     {name: "Asset 3", status: true},
     {name: "Asset 4", status: true},
     {name: "Asset 5", status: true},
     {name: "Asset 6", status: true},
     ];
    
     $scope.delete = function(item){
     item.status = !item.status;
     }
     $scope.itemClick= function(item){
     console.log(item);
     }
    });
    

    HTML 代码。

    <body layout="column" layout-fill ng-app="myApp" ng-cloak ng-controller="TempController">
    
     <div layout="row" layout-align="center end" class="resolvedSwitch">
      <md-switch ng-model='tempSwitch'>
      SHOW-DISABLED
      </md-switch>
    </div>
     <md-content layout="column" flex style='background-color:#d1d1d1'>
       <md-list>
         <md-list-item ng-click="itemClick(item)" ng-repeat="item in data" layout-align="start center" ng-show="item.status || tempSwitch">
           <span>{{item.name}} </span>
           <span flex></span>
           <span>{{item.status}}</span>
           <md-button aria-label="Delete Asset" class="md-icon-button md-warn" ng-click="delete(item)">
                  <md-icon>D</md-icon>
           </md-button>
           <md-divider></md-divider>
          </md-list-item>
       </md-list>
     </md-content>
    </body>
    

    这是Codepen 的工作示例。

    【讨论】:

    • 所以我接受了您的建议并主要解决了我的问题,我已经更新了问题中的代码。我仍然必须按要求保留 md-virtual-repeat-container。我现在遇到的问题是,残疾资产正在变得杂乱无章,它没有移动到顶线。本质上它隐藏了所有没有禁用的资产并保持禁用的位置相同。我在问题中放了一张图片
    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 2023-02-08
    • 2019-10-15
    • 2020-11-19
    • 2020-09-20
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多