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

- 2,506
- 4
- 18
- 30
-
@Khmerbridge glad it helped! please consider also to upvote the post, to give him more visibility in the future – Andi Pavllo Apr 19 '15 at 04:46