在ionic中,modal也是添加控制器写服务的~
在modal.html页面中增加控制器:ng-controller="aboutCtrl"
记住要给这个添加控制器。
头部使其关闭按钮,只需要使用ng-click = "hide()"
在app.js中初始化modal:
$rootScope.aboutModal = modalSvc.createModal('templates/about.html');
在控制器下要使用:
$scope.openAboutModal = function(){
$rootScope.aboutModal.show();
}
modalSvc.js:
记住在最后要返回。
/** * * * 初始化: * var $rootScope.oneModal = modalSvc.createModal(templateUrl); * * * 指定控制器 * <ion-view class="modal" ng-controller="loginCtrl"> * * * 打开modal并传递数据 * oneModal.show(params); * 通过参数params可以向modal中传递数据 * <span>{{params.title}}</span> * * * 通过完成事件获得结果 * function onModalComplete(result) { * } * oneModal.show(params).then(onModalComplete); * 其中result 就是modal关闭时的结果,也是hide函数传回的值: hide(result) * 如果通过其他方式关闭modal,也会调用onModalComplete,但result为undefined * * * 关闭modal * oneModal.hide(result) * result作为modal的结果,传回调用者 * * * 在模板中关闭modal * <button ng-click="hide(true)">OK</button> * <button ng-click="hide()">Cancel</button> * * * 指定每次modal打开时要执行的代码 * oneModal.scope.events.onShow = function ($scope) {} * * * 指定每次modal关闭时要执行的代码 * oneModal.scope.events.onHide = function ($scope) {} * */ angular.module('modalSvc', ['ionic']).factory('modalSvc', [ '$q', '$rootScope', '$ionicModal' , function ($q, $rootScope, $ionicModal) { function createModal(templateURL) { var modalService = { scope: $rootScope.$new(), modalWindow: null, show: function (params) { this.scope.q = $q.defer(); this.scope.params = params || {}; if (this.modalWindow) { var scope = this.scope; this.modalWindow.show().then(function () { if (scope.events.onShow) { scope.events.onShow(scope); } }); } return this.scope.q.promise; }, hide: function (result) { if (this.modalWindow) { var scope = this.scope; this.modalWindow.hide().then(function () { if (scope.events.onHide) { scope.events.onHide(scope); } }); } if (this.scope.q) { this.scope.q.resolve(result); this.scope.q = undefined; } } }; modalService.scope.events = { // onShow // onHide }; modalService.scope.hide = function (result) { modalService.hide(result); }; $ionicModal.fromTemplateUrl(templateURL, function (modal) { modalService.modalWindow = modal; }, { scope: modalService.scope, animation: 'slide-in-up' }); return modalService; } return {createModal: createModal}; } ]);