Search code examples
javascriptangularjsdialogonsen-ui

how can I share data between two <ons-template> ?use angularjs and onsen ui


I'm a new with onsen ui and angularjs ,today I get one problem with this here is my HTML code :

<ons-page ng-controller="DialogController">
  <ons-toolbar>
    <div class="center">Dialog
    {{dataShow.username}}
    </div>
  </ons-toolbar>
  <ons-list >
   <ons-list-item ng-click="show('navigator.html')" modifier="tappable">
     Navigator
   </ons-list-item>
  </ons-list>
</ons-page>

<ons-template  id="navigator.html">
  <ons-dialog style="height: 160px;" var="naviDialog" cancelable>

    <ons-navigator var="myNav">
      <ons-toolbar inline>
        <div class="center">
          Navigator  {{dataShow.username}}
        </div>
      </ons-toolbar>

      <div style="text-align: center">
        <p>
          This is a dialog with a navigator.
        </p>

        <p>
          <ons-button onclick="naviDialog.hide()">Close</ons-button>
          <ons-button onclick="myNav.pushPage('next.html')">Next</ons-button>
        </p>
      </div>
    </ons-navigator>
  </ons-dialog>        
</ons-template>

and my javascript looked like this:

    ons.bootstrap()

.controller('DialogController', function($scope) {
  $scope.dataShow = {
    username : 'huangqiang',
    age :'25'
  };

  $scope.next = function() {
    $scope.dialog.hide();
    ons.createDialog('dialog2.html').then(function(dialog) {
      dialog.show();
    });
  }

  $scope.show = function(dlg) {
    ons.createDialog(dlg).then(function(dialog) {
      dialog.show();
    });
  }
});

the question is I can't get result with {{dataShow.username}} in ,did any one can help me out ?


Solution

  • You need to create a separate controller and use a service to pass the data to the controller.

    HTML snippet

    <ons-dialog style="height: 90%; width: 90%" var="naviDialog" cancelable ng-controller="newsFeedCtrl">
    

    make sure to add the ng-controller on the ons-dialog section instead of the template section

    JS snippet

    .service("NewsFeedSelectedData", function () {
            this.title = "";
            this.link = "";
          })
          .controller("newsFeedCtrl", ['$scope', '$sce', 'NewsFeedSelectedData', function ($scope, $sce, NewsFeedSelectedData) {
            $scope.title = NewsFeedSelectedData.title;
            $scope.link = $sce.trustAsResourceUrl(NewsFeedSelectedData.link);
          }])