angularjs – Angular / Ionic中可重复使用的模态
发布时间:2020-12-17 08:32:51 所属栏目:安全 来源:网络整理
导读:在使用Ionic的AngularJS中,我希望能够从不同的控制器调用一个模态,而不必复制与模态相关的代码. 以下是如何创建模态(缩写为http://learn.ionicframework.com/formulas/making-modals/). HTML: div class="card" ng-controller='MainCtrl' ng-click="openMod
在使用Ionic的AngularJS中,我希望能够从不同的控制器调用一个模态,而不必复制与模态相关的代码.
以下是如何创建模态(缩写为http://learn.ionicframework.com/formulas/making-modals/). HTML: <div class="card" ng-controller='MainCtrl' ng-click="openModal()"> Click here to open the modal </div> JS: app.controller('MainCtrl',function($scope,$ionicModal) { $ionicModal.fromTemplateUrl('contact-modal.html',{ scope: $scope,animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal }) $scope.openModal = function() { $scope.modal.show() } // functions for this modal // ... }) 现在这一切都很好,但是如果我想从不同的控制器打开具有相同功能的相同模态,我将不得不复制与之相关的所有代码. 我如何抽象这个以使我的模态可以从不同的控制器重用和调用? 理想情况下,我希望每个模态都有自己的“控制器”(或类似的概念),而不是必须将其所有代码放入控制器中,无论打开它的是什么.
这是指令的完美场景.
指令代码: app.directive('myPopUp',['$ionicModal',function($ionicModal) { return { restrict: 'E',scope: { externalScope : "=" } replace: true,templateUrl: 'path/to/your/template',link: function($scope,$element,$attrs) { $ionicModal.fromTemplateUrl('contact-modal.html',{ scope: $scope.externalScope,animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal }); $scope.externalScope.openModal = function() { $scope.modal.show() }; } }; }]); 和你的控制器: app.controller('MainCtrl',['$scope',function($scope) { $scope.externalScope = {} }); 每当你想要将其包含在部分中时,只需添加: <my-pop-up externalScope="externalScope"></my-pop-up> 该指令可以通过externalScope属性访问控制器,反之亦然.您可以从控制器调用$scope.externalScope.openModal(),它将触发您的指令模式打开. 希望这很有帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |