Ionic教程-modal的使用

本文介绍了如何使用Ionic框架的$ionicModal指令来创建模态对话框,包括使用ng-template模板创建对话框内容的方法,并详细展示了如何在JS中加载和控制对话框的显示与隐藏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ionic提供了$ionicModal指令来创建modal模态对话框。modal的内容可以来自字符串,或者是本地的ng-template模板,或者是远程url。这里我们使用ng-template模板。

首先,我们创建一个简单的UI界面,提供一个按钮来打开modal。

<ion-header-bar class="bar-energized">
  <h1 class="title">Contact Info</h1>
</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>


<script id="contact-modal.html" type="text/ng-template">
  <div class="modal">
    <ion-header-bar>
      <h1 class="title">Edit Contact</h1>
    </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>




在实际使用的时候,可以把模板放到一个单独的文件中。为了加快速度,还可以把模板添加到templateCache中,这些我们后面会讲到。
下面我们在js里面加载modal,以及控制modal的显示。
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();
  });
})

添加$ionicModal依赖,便可以使用$ionicModal。$ionicModal使用了deferred来异步加载模板,加载完成后会返回modal对象,这里使用了$scope.modal = modal来接收这个modal对象,从而控制这个modal。这样我们就实现了一个modal。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值