How to execute a function defined in a controller attached to a previous page after ons.navigator.popPage() ?

StackOverflow https://stackoverflow.com/questions/23273697

Domanda

I discover Onsen UI and I have a problem :

1- I defined 2 pages page-1.html and page-2.html with a controller attached (page1Ctrl and page2Ctrl).

2- I defined a function in page1Ctrl to go to the page-2.html :

$scope.ons.navigator.pushPage('page-2.html');

which executes page2Ctrl

3- In this page, i have a button which executes a code that returns on page-1.html (with popPage()). This function is attached to page2Ctrl :

function page2Ctrl($scope) {
    $scope.functionToPopPage = function() {

        // >>> Here I would like to execute a function attached to page1Ctrl

        $scope.ons.navigator.popPage();
    };
}

4- then, i want to launch a function defined in the page1Ctrl, how could i process it ?

Thanks

È stato utile?

Soluzione

You can share controller's function with service. Try to register the function you want to attache to both page1Ctrl and page2Ctrl, then call the shared function from page2Ctrl. The following code is a example.

page1.html

<ons-page class="center" ng-controller="page1Ctrl">
  <ons-navigator-toolbar
    title="Welcome">        
  </ons-navigator-toolbar>
  <h1>Page 1</h1>
  <ons-button ng-click="goToPage2()">Push Page 2</ons-sbutton>  
</ons-page>

page2.html

<ons-page class="center" ng-controller="page2Ctrl">
  <ons-navigator-toolbar title="Page 2">        
  </ons-navigator-toolbar>
  <h1>Page 2</h1>
  <button class="topcoat-button" ng-click="popToPage1()">Pop Page1</button>
</ons-page>

app.js

var myApp = angular.module('myApp', ['onsen.directives']);


myApp.factory('pageService', function(){
    return{
        foo : function()
            alert('foo');
        }
    }        
});

myApp.controller('page1Ctrl', function($scope, pageService){    
    $scope.goToPage2 = function(){
        pageService.foo();
        $scope.ons.navigator.pushPage("page2.html");        
    }
});

myApp.controller('page2Ctrl', function($scope, pageService){    
    $scope.popToPage1 = function(){
        pageService.foo();
        $scope.ons.navigator.popPage();        
    }
});

Altri suggerimenti

idea:

  • You declare a global variable
  • In the controller you page1Ctrl assigns your function to this variable
  • And you used in page2Ctrl :)

ex :

var heloWord;

function page1Ctrl($scope) {
  heloWord = function() {
    console.log('Helo Word');
  }
}

function page2Ctrl($scope) {
  $scope.functionToPopPage = function() {
    heloWord();
    $scope.ons.navigator.popPage();
  };
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top