What is the idiomatic way of communicating between Onsen popover and its parent?

This is what I have . First script:

ons.bootstrap(); .controller('AppController', function($scope) { $scope.greeting = "Hello!"; ons.createPopover('popover.html').then(function(popover) { $scope.popover = popover; popover.on('preshow', function() { popover._scope.greeting = $scope.greeting; }); popover.on('posthide', function() { $scope.greeting = popover._scope.greeting; $scope.$apply(); }); }); }); 

And the page:

 <ons-page ng-controller="AppController"> <ons-toolbar> <div class="center">Popover</div> </ons-toolbar> <div style="margin-top: 100px; text-align: center"> <ons-button modifier="light" ng-click="popover.show($event)">Show popover</ons-button> </div> <div style="margin-top: 100px; text-align: center">{{greeting}}</div> </ons-page> <ons-template id="popover.html"> <ons-popover direction="up down" cancelable> <div style="text-align: center; opacity: 0.8;"> <input style="margin: 20px" type="text" ng-model="greeting" /> </div> </ons-popover> </ons-template> 

This seems to work for me, but I'm not sure about the popover._scope part. Should it be accessible this way? I can't seem to find another way.

So what is the idiomatic way to do this? And what are some good examples?

Thanks.

+5
source share
1 answer

You can use the parentScope parameter to make popover coverage a stream of the AppController scope:

 module.controller('AppController', function($scope) { ons.createPopover('popover.html', {parentScope: $scope}); }); 

You now have several options for interacting between areas. Since the popover scope is a descendant of the AppController scope, you can, for example, use $scope.$emit() to generate events when the value changes:

 module.controller('AppController', function($scope) { $scope.greeting = 'Hello!'; ons.createPopover('popover.html', {parentScope: $scope}).then(function(popover) { $scope.popover = popover; }); $scope.$on('update', function(event, value) { $scope.greeting = value; }); }) .controller('PopoverController', function($scope) { $scope.$watch('greeting', function(value) { $scope.$emit('update', value); }); }); 

I made a simple example: http://codepen.io/argelius/pen/avmqOP

You can also use ngModel to access the value, but keep in mind that this is actually grandparents, so in this case you need to do ng-model="$parent.$parent.greeting" , which is not very nice.

I would recommend an approach to events.

+5
source

Source: https://habr.com/ru/post/1232172/


All Articles