溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Ionic最佳實踐-使用模態(tài)窗口modal

發(fā)布時間:2020-07-07 04:47:01 來源:網(wǎng)絡 閱讀:852 作者:betree 欄目:開發(fā)技術

原文地址:Ionic最佳實踐-使用模態(tài)窗口modal

模態(tài)窗口的結構

在Ionic中,模態(tài)窗口通過$ionicModal提供。他易于使用且非常強大,詳細信息請參考$ionicModal文檔。Ionic中的模態(tài)窗口可以使用模板字符串或URL創(chuàng)建。本文將使用URL。

模態(tài)窗口創(chuàng)建時綁定到一個scope,這個scope可以用來傳遞數(shù)據(jù)。然而,在更復雜的情況下,通過服務來訪問共享數(shù)據(jù)是最好的做法。

 

制作模態(tài)窗口的標記

創(chuàng)建模態(tài)窗口非常簡單。首先,讓我們來創(chuàng)建我們的用戶界面。這個小例子將會展示一條聯(lián)系人信息,點擊后允許對它進行編輯。

<ion-header-bar class="bar-energized">
 <h2 class="title">Contact Info</h2>
</ion-header-bar>
<ion-content>
 <div class="card" ng-controller='MainCtrl' ng-click="openModal()">
  <div class="item item-divider">
   `contact`.`name`
  </div>
  <div class="item item-text-wrap">
   `contact`.`info`
  </div>
 </div>
</ion-content>

 現(xiàn)在,看起來還沒有什么特別的,唯一與模態(tài)窗口相關的是一個scope函數(shù):openModal()。還缺少我們的modal部分。直接在當前標記中添加它。

<script id="contact-modal.html" type="text/ng-template">
  <div class="modal">
    <ion-header-bar>
      <h2 class="title">Edit Contact</h2>
    </ion-header-bar>
    <ion-content>
      <div class="list">
        <label class="item item-input">
          <span class="input-label">Name</span>
          <input type="text" ng-model="contact.name">
        </label>
        <label class="item item-input">
          <span class="input-label">Info</span>
          <input type="text" ng-model="contact.info">
        </label>
      </div>
      <button class="button button-full button-energized" ng-click="closeModal()">Done</button>
    </ion-content>
  </div>
</script>

在生產(chǎn)環(huán)境中,你可能想把模板標記放入獨立文件中或把它們添加到模板緩存中。與Ionic中其他使用模板的部分一樣,Angular將先從模板緩存中搜索需要的文件。

顯示模態(tài)窗口

模態(tài)窗口的控制器代碼非常簡單。確保在控制器中注入依賴項$ionicModal。

 

app.controller('MainCtrl', function($scope, $ionicModal) {
  $scope.contact = {
    name: 'Mittens Cat',
    info: 'Tap anywhere on the card to open the modal'
  }
  $ionicModal.fromTemplateUrl('contact-modal.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal
  }) 
  $scope.openModal = function() {
    $scope.modal.show()
  }
  $scope.closeModal = function() {
    $scope.modal.hide();
  };
  $scope.$on('$destroy', function() {
    $scope.modal.remove();
  });
})

Ionic的模態(tài)窗口使用了一個異步deferred。這樣可以異步訪問模板緩存和構建模態(tài)窗口。我們可以為模態(tài)窗口提供一個scope對象,否則他將使用$rootScope??梢詾槟B(tài)窗口的打開動作指定過度動畫效果。官方文檔中描述了更多過度效果。

一旦模態(tài)窗口構建完畢,異步完成函數(shù)允許我們設置一個$scope.modal變量。模態(tài)窗口有一些函數(shù)。在本例中,我們關心show, hide和remove函數(shù)。remove函數(shù)特別重要。通過監(jiān)聽scope對象的$destroy事件,我們可以確保對模態(tài)窗口對象進行垃圾回收。忽略它將會導致你的程序出現(xiàn)內(nèi)存泄漏。

回顧

模態(tài)窗口是一個很強大的用戶界面組件,通過Ionic來展現(xiàn)和利用它是一件很輕松的事情。


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI