How to hide popover in onsen ui

杀马特。学长 韩版系。学妹 提交于 2020-01-06 15:07:21

问题


I have been following Drop down option menu using onsen UI, but I want to cancel the popover when tapping on it. Any idea.


回答1:


Usually, you can just hide it with popover.hide(), but it seems there is a bug when you try to use again the same controller with a popover containing a list (the browser gets stuck and the CodePen sample get bugged). That's why you need to create another controller to hide the popover and a service to share the popover between the two controllers (Here you can find a working CodePen).

var app = ons.bootstrap();

app.controller('DropdownController', function($scope, myService) {
  ons.createPopover('popover.html').then(function(popover) {
    $scope.popover = popover;
    myService.setPopover($scope.popover);
  });
});

app.controller('MyController', function($scope, myService) {
  $scope.destroyPopover = function() {
    $scope.popover = myService.getPopover();    
    $scope.popover.hide();
  }
});

app.service("myService", function(){
  var sharedPopover
  
  var setPopover = function(pop){
    sharedPopover = pop;
  };
  
  var getPopover = function(){
    return sharedPopover;
  };
  
  return {
    setPopover: setPopover,
    getPopover: getPopover,
  };
});

After, just add the controller in the new popover.html template, and the ng-click="destroyPopover()" directive to the ons-list-item. Doing that, the popover will be hidden every time you click the list element.

<ons-template id="popover.html" >
  <ons-popover direction="down" cancelable >
    <ons-list ng-controller="MyController">
      <ons-list-item modifier="tappable" ng-click="hidePopover()">Option 1</ons-list-item>
      <ons-list-item modifier="tappable" ng-click="hidePopover()">Option 2</ons-list-item>
      <ons-list-item modifier="tappable" ng-click="hidePopover()">Option 3</ons-list-item>
    </ons-list>
  </ons-popover>
</ons-template>

EDIT

There is another way to hide the popover without using an AngularJS Service. Since Onsen UI 1.3 release it's possible to pass scope for dialogs and popover, when creating them with ons.createDialog(), ons.createPopover() and ons.createAlertDialog(). (source).

When creating a dialog the following syntax can be used:

ons.createDialog('dialog.html', {parentScope: $scope}).then(function(dialog) {
  $scope.dialog = dialog;
});

and use

<ons-list-item modifier="tappable" ng-click="popover.hide()">Option 1</ons-list-item>

You can find a working CodePen example HERE.



来源:https://stackoverflow.com/questions/29713320/how-to-hide-popover-in-onsen-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!