ionic2 + 按名字分組的手機通訊錄 組件

來源:互聯網
上載者:User

標籤:ati   asp   off   mat   log   oid   case   cts   ==   

ionic2 名字分組手機通訊錄 組件實現以下功能
  • 擷取手機通訊錄資料
  • 資料分組顯示(中文英文正確分組)
  • 點擊索引進行跳轉
  • 滾動到特殊位置進行特別處理
  • 連絡人查詢
預覽

contacts.html
<ion-header>  <ion-navbar>    <ion-title>選擇連絡人</ion-title>  </ion-navbar></ion-header><ion-content padding> <ion-searchbar [debounce]="searchDebounce" [(ngModel)]="searchKey"   [showCancelButton]="shouldShowCancel"   (ionInput)="onInput($event)" (ionCancel)="onCancel($event)">  </ion-searchbar><ion-row style="height: 88%">     <ion-col col-11 >    <!-- <div *ngIf="!contactList||contactList.length<=0">      <div >手機通訊錄沒有連絡人</div>    </div> -->    <ion-scroll #scroll scrollY="true" style="height: 100%">        <ion-item-group *ngFor="let contactItem of contactList" >          <ion-item-divider color="light" id="index_{{contactItem.letter}}">            {{contactItem.letter}}          </ion-item-divider>          <ion-item *ngFor="let contact of contactItem.contact" (click)="selectContact(contact)">           <!--  <ion-avatar item-start>              <img src="assets/icon/favicon.ico">            </ion-avatar> -->            <h2> {{contact.displayName}}</h2>            <p>手機:{{contact.phoneNumbers[0].value}}</p>          </ion-item>        </ion-item-group>    </ion-scroll>  </ion-col>  <ion-col col-1 class="index-num">    <div  *ngFor="let indexItem of contactIndex" (click)="goToIndex(indexItem)">{{indexItem}}</div>  </ion-col></ion-row> </ion-content>
contacts.scss
.index-num{  color:blue;    font-size: 13px;}.scroll-content{  padding:0px !important}.red-index{  color:red;}
contacts.component.ts
import { Component, ViewChild } from '@angular/core';import { NavController, NavParams } from 'ionic-angular';import { Contacts } from '@ionic-native/Contacts';import { CommonUtil } from '../common.util';@Component({  selector: 'contacts',  templateUrl: 'contacts.html'})/**  連絡人群組件  @author 0o曉月メ*/export class ContactsComponent {  @ViewChild('scroll') scroll: any;  private contactList: any;  private contactIndex: Array<string>;  private searchKey: string;  private shouldShowCancel: boolean;  public isCordova: boolean;  public searchDebounce: number = 600;  public currentId:string;  private isIOS:boolean;  constructor(private commonUtil: CommonUtil, private contacts: Contacts, public navCtrl: NavController, public navParams: NavParams) {    this.initData();  }  /**    滾動到特定位置做特殊處理 demo  */  ngAfterViewInit() {    if(!this.isCordova){      this.scroll.addScrollEventListener((event) => {        let positionN = document.getElementById('index_' + 'N').offsetTop;        let positionS = document.getElementById('index_' + 'S').offsetTop;        if (event.currentTarget.scrollTop > positionN && event.currentTarget.scrollTop < positionS) {          console.log('在模組N');          this.currentId ='N';        } else if (event.currentTarget.scrollTop > positionS) {          console.log('在模組S');          this.currentId ='S';        } else {          this.currentId ='';          console.log('還沒到達N模組');        }      });    }  }  initData(): void {    this.searchKey = "";    this.shouldShowCancel = true;    this.isCordova = this.commonUtil.isCordova();    this.isIOS = this.commonUtil.isIOS();    this.contactIndex = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');    //alert(  .isCordova)    if (this.isCordova) {      let opts = {        filter: "",        multiple: true,        hasPhoneNumber: true,        fields: ['displayName', 'name']      };      let me = this;      this.contacts.find(['displayName', 'name'], opts)        .then((contactList) => {          me.contactList = contactList;          console.log(contactList)          me.generateContactGroup(contactList);        }, (error) => {          console.log(error);        });    } else {      let data = this.initBrowserData();      this.generateContactGroup(data);    }  }  /**    調用callback方法傳送選擇的聯絡資訊,再跳回上一個頁面    demo:    this.navCtrl.push(ContactComponent,{callback:this.callBackTest,scope:this});        callBackTest(param):Promise<any>{      let me = this;      return new Promise(resolve => {        me.recommendPhone = param.phoneNumbers[0].value;;        console.log(me.recommendPhone);        resolve('success');      })    }  */  selectContact(contact): void {    if (!contact) contact = null;    let callback = this.navParams.get("callback");    let scope = this.navParams.get("scope");    if (!callback || !scope) {      alert('Callback function or scope is not provide!');      return;    }    callback.call(scope, contact).then(() => {      this.navCtrl.pop();    });  }  onInput($event): void {    console.log($event);    if (this.isCordova) {      let opts = {        filter: this.searchKey,        multiple: true,        hasPhoneNumber: true,        fields: ['displayName', 'name']      };      this.contacts.find(['displayName', 'name'], opts)        .then((contactList) => {          this.contactList = contactList;          console.log(contactList)          this.generateContactGroup(contactList);        }, (error) => {          console.log(error);        });    } else {      let data = this.initBrowserData();      this.generateContactGroup(data);    }  }  onCancel($event): void {  }  /**    連絡人分組  */  generateContactGroup(arr) {    if (!String.prototype.localeCompare) {      console.error('localeCompare function not found');      return [];    }    //enTmp cnArray    let enResult = this.sortEnContacts(arr);    console.log('generateContactGroup=>enResult', enResult);    let sortResult = enResult.enTmp;    let cnArray = enResult.cnArray;    let enKey = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');    let letters = "*abcdefghjklmnopqrstwxyz".split('');    let zh = "阿八嚓噠妸發旮哈譏哢垃痳拏噢妑七呥扨它穵夕丫帀".split('');    for (let i = 0; i < letters.length; i++) {      let letter = letters[i].toUpperCase();      let curr;      if (sortResult[letter]) {        curr = sortResult[letter];      } else if ('*' != letters[i]) {        curr = sortResult[letter] = [];      }      for (var j = 0; j < cnArray.length; j++) {        if ((!zh[i - 1] || zh[i - 1].localeCompare(cnArray[j].displayName,'zh') <= 0) && cnArray[j].displayName.localeCompare(zh[i],'zh') == -1) {          curr.push(cnArray[j]);        }      }    }    let contactResult = [];    for (let k = 0; k < enKey.length; k++) {      let item = sortResult[enKey[k]];      if (item && item.length > 0)        contactResult.push({ letter: enKey[k], contact: item });    }    console.log(contactResult);    this.contactList = contactResult;    return contactResult;  }  /**    連絡人英文名字先分組  */  sortEnContacts(contactList: Array<any>) {    let en = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',      'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];    let enTmp = {};    let cnArray = [];    for (var i = 0; i < contactList.length; i++) {      if( this.isIOS && this.isCordova){        contactList[i].displayName =  contactList[i].name.formatted;      }      let letter = contactList[i].displayName.toUpperCase().charAt(0);      if (en.indexOf(letter) >= 0) {        if (enTmp[letter] == undefined) {          enTmp[letter] = []        }        enTmp[letter].push(contactList[i]);      } else {        cnArray.push(contactList[i])      }    }    return { 'enTmp': enTmp, 'cnArray': cnArray };  }  goToIndex(letter): void {    console.log(letter);    let target = document.getElementById('index_' + letter);    if (target)      this.scroll._scrollContent.nativeElement.scrollTop = target.offsetTop;  }  initBrowserData(): Array<any> {    return [{ displayName: 'jack', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '陳先生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '吳先生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '王先生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '林小姐', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '馮先生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '蔣生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '黃生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'jack', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'mike', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'ivin', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'kevin', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '誰', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '張小姐', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '好', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'tag', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'ok', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'jack', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'fary', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'note', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'may', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'moon', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '月', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '輝', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '明', phoneNumbers: [{ value: "13626578952" }] },    { displayName: '郭生', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'kity', phoneNumbers: [{ value: "13626578952" }] },    { displayName: 'marry', phoneNumbers: [{ value: "13626578952" }] },    ];  }}

ionic2 + 按名字分組的手機通訊錄 組件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.