温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Ionic最佳实践-使用模态窗口modal

发布时间:2020-07-07 04:47:01 来源:网络 阅读:839 作者:betree 栏目:开发技术

原文地址:Ionic最佳实践-使用模态窗口modal

模态窗口的结构

在Ionic中,模态窗口通过$ionicModal提供。他易于使用且非常强大,详细信息请参考$ionicModal文档。Ionic中的模态窗口可以使用模板字符串或URL创建。本文将使用URL。

模态窗口创建时绑定到一个scope,这个scope可以用来传递数据。然而,在更复杂的情况下,通过服务来访问共享数据是最好的做法。

 

制作模态窗口的标记

创建模态窗口非常简单。首先,让我们来创建我们的用户界面。这个小例子将会展示一条联系人信息,点击后允许对它进行编辑。

<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>

 现在,看起来还没有什么特别的,唯一与模态窗口相关的是一个scope函数: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>

在生产环境中,你可能想把模板标记放入独立文件中或把它们添加到模板缓存中。与Ionic中其他使用模板的部分一样,Angular将先从模板缓存中搜索需要的文件。

显示模态窗口

模态窗口的控制器代码非常简单。确保在控制器中注入依赖项$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的模态窗口使用了一个异步deferred。这样可以异步访问模板缓存和构建模态窗口。我们可以为模态窗口提供一个scope对象,否则他将使用$rootScope。可以为模态窗口的打开动作指定过度动画效果。官方文档中描述了更多过度效果。

一旦模态窗口构建完毕,异步完成函数允许我们设置一个$scope.modal变量。模态窗口有一些函数。在本例中,我们关心show, hide和remove函数。remove函数特别重要。通过监听scope对象的$destroy事件,我们可以确保对模态窗口对象进行垃圾回收。忽略它将会导致你的程序出现内存泄漏。

回顾

模态窗口是一个很强大的用户界面组件,通过Ionic来展现和利用它是一件很轻松的事情。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI