Pass scope between 2 pages

Hello all

im new to ionic im devloping a sample app . i want to display the data in array in page 1 to table in page 2. can anyone help me how to pass data between 2 pages .i have attached screenshot

page 1:

page 2:

This looks like ionic 2, OP is posting in Ionic 1 folder.
I’m currently on my phone, but as soon as I have my project I’ll give you my solution.
First look into stateParameters, that’s how I did it.

Create functions in your Factory, for example: getData(), which can be called from any pages.

you were right, therefor I deleted my Ionic2 solution.

in Ionic1, to pass parameters.

1. In your app.js, define your route for accepting or requesting params. Something like

.state('app.page2', {
    url: '/page2/:testParam',
  
2. Then, when you call the page, for example in your html code, pass the param

<div class="item" ui-sref="app.page2({testParam: 'awesome'})"></div>

 3. In your Page2, inject $stateParams and get the value as following example written in typescript

export class Page2 {
public static $inject = ['$stateParams'];

constructor(private $stateParams:angular.ui.IStateParamsService) {
      this.$scope.$on('$ionicView.beforeEnter', (event:ng.IAngularEvent, data:ionic.StateParams) => {
           var test:string = this.$stateParams['testParam'];
      }
}
}

Hope that could help. But I’m agree there are different solution, passing params is one, using a service or factory as proposed oasisari is another one.

1 Like

can you give a sample code for the above layout ??? it would be helpfull for me i have tried all methods but still im not getting the output.

Not really, don’t have more code, futhermore I work with Ionic2. But you could parse your codes here and I will have a look.

page 1.html

<div class="jumbotron">
    <form class="form-horizontal" role="form">
        <div class="form-group">
            <label class="control-label col-sm-2" for="email">Name:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="name" placeholder="Enter Name" ng-model="contact.name">
                <div>{{contact.name}}
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2" for="pwd">Email:</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="email" placeholder="Enter Email" ng-model="contact.email">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2" for="pwd">Mobile No:</label>
            <div class="col-sm-10">
                <input type="tel" class="form-control" id="mobile" placeholder="Enter Mobile" ng-model="contact.mobile">
            </div>
        </div>
        {{contact}}
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" ng-click="submit(contact)">Submit</button>
            </div>
        </div>
        <!-- <div class="col-sm-offset-2 col-sm-10">
               <a href="#page2">NEXT</a>
            </div> -->
    </form>
</div>

page 2.html

<div class="jumbotron">
        <table class="table table-hover table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Mobile</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="x in contacts track by $index">
                    <td>{{$index+1}}</td>
                    <td ng-model="current.name">{{x.name}} </td>
                    <td ng-model="current.email">{{x.email}}</td>
                    <td ng-model="current.mobile">{{x.mobile}}</td>
                    <!-- <td>
                        <button type="button" class="btn btn-primary" ng-click="removeItem(x)">
                        <span class="glyphicons glyphicons-edit"></span></button>
                        <button type="submit" class="btn btn-primary" ng-click="editItem(x)">Edit</button>
                    </td> -->
                    <td>
					  <button type="button" class="btn btn-primary" ng-click="removeItem(x)">
					    <i class="fa fa-trash-o" aria-hidden="true"></i>
					  </button>
					  <button type="button" class="btn btn-danger" ng-click="editItem(x)">
					  <i class="fa fa-pencil" aria-hidden="true"></i>
					  </button>
					</td>
                </tr>
            </tbody>
        </table>
    </div>

    <form class="form-horizontal" role="form">
        <div class="form-group">
            <label class="control-label col-sm-2" for="email">Name:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="name" placeholder="Enter Name" value="{{current.name}}" ng-model="current.name">
                
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2" for="pwd">Email:</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="email" placeholder="Enter Email" value="{{current.email}}" ng-model="current.email">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2" for="pwd">Mobile No:</label>
            <div class="col-sm-10">
                <input type="tel" class="form-control" id="mobile" placeholder="Enter Mobile" value="{{current.mobile}}" ng-model="current.mobile">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" ng-click="save(current)">Submit</button>
            </div>
        </div>
        
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-primary" ng-click="previous()">Add More</button>
            </div>
        </div>
    </form>

app.js

    // Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider

  // setup an abstract state for the tabs directive
    .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'templates/tabs.html'
  })

  // Each tab has its own nav history stack:

  .state('tab.home', {
    url: '/home',
    views: {
      'tab-dash': {
        templateUrl: 'templates/home.html',
        
      }
    }
  })

  .state('tab.chats', {
      url: '/chats',
      views: {
        'tab-chats': {
          templateUrl: 'templates/tab-chats.html',
          
        }
      }
    })
    .state('tab.chat-detail', {
      url: '/chats/:chatId',
      views: {
        'tab-chats': {
          templateUrl: 'templates/chat-detail.html',
          controller: 'ChatDetailCtrl'
        }
      }
    })

  .state('tab.account', {
    url: '/account',
    views: {
      'tab-account': {
        templateUrl: 'templates/tab-account.html',
        controller: 'AccountCtrl'
      }
    }
  });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/home');

});

controller.js

a ngular.module(‘starter.controllers’, [])

.controller('DashCtrl', function($scope) {})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
})

.controller('Home', function($scope,contact){

    $scope.contacts = [];
        /*$scope.contact ={};*/
        console.log($scope.contacts.length);
        console.log($scope.contacts);

        $scope.submit = function(contact) {
            // console.log('am in');

            $scope.contacts.push(contact);
            console.log($scope.contacts);
            refresh();
        };

        var refresh = function() {
            $scope.contact = '';
        };
        $scope.removeItem = function(x) {
            var index = $scope.contacts.indexOf(x);
            alert("deleting" + index);
            $scope.contacts.splice(index, 1);

        }
        $scope.editItem = function(x) {
            $scope.current = x;
        }
        $scope.save=function(x){
          $scope.current={};

        }

    


})

I had a quick look at your code. Is it the right code?

I mean you didn’t use Ionic at all. Your sample code look more like an angular website.

Look, no Ionic declaration

var myApp = angular.module('demo', ['ngRoute']);

where it should be at least

 var myApp = angular.module('demo', ['ionic']);

ya its angular website i have check this code in (WAMP). we can use the same code for ionic as well because ionic in mainly based on angularjs just we have to make few modifications as you said

var myApp = angular.module(‘demo’, [‘ngRoute’]);

should be

var myApp = angular.module(‘demo’, [‘ionic’]);

my question is its working perfectly in localhost (wamp) but not working in ionic app .

i read in blog to use factory or service method to pass the scope bwt 2 views.

you can use ng-model and pass it to the next controller or if you want to use it globally pass it to the factory or service…

ng-model is not working in ionic to pass between two views… can you give a example for a factory method or service method ??

have you install ngCordova to your app??

will it be automatically created when i start a ionic template or do i have to install in manually ? i have ionic sidemenu template .

you need to install it… www.ngcordova.com please see this link for the installation process…

mmmh ok sorry I don’t get, don’t see how you could use Ionic without loading Ionic and how it could work on a mobile phone if you don’t load Ionic.

but well whatever, if you find a solution passing your parameters with a service (“angular style”) then good for you and happy to hear it worked :wink:

of course you need to inject ionic to your module like var myApp = angular.module(‘demo’, [‘ionic’]); where I see that your code in module is only ngRoute…

yes you are correct. we need to include ionic in mobile

angular.module(‘starter’, [‘ionic’, ‘starter.controllers’,‘ion-floating-menu’])

my point is even if i include ionic im not getting data’s.

probably you need to install ngCordova to your app…

Understand. Well then that was the first step, then if you would have wanted to pass parameters thru view without services you would have to do some other improvements. But passing arguments with services is a good way to do it. Furthermore it will allow you to handle back action more easily

i have updated my code as u said plz chk above and let me know !!