Search code examples
angularjsionic-frameworkionic-view

$stateParams variable not defined if the view is accessed directly?


I have two views VIEW1 and VIEW2. Usually VIEW1 does not need $stateParams vars to function if accessed directly. But if accessed from VIEW2 I need to pass $stateParams vars to VIEW1 from VIEW2.

app.controller('View1Ctrl', function($scope, $stateParams, $state) {

   $scope.varView1 = $stateParams.view2Data.varView2;

)}

.state('app.view1', {
  url: '/view1',
  params: {view2Data: null },
  views: {
    'menuContent': {
      templateUrl: 'templates/view1.html',
      controller: 'View1Ctrl'

    }
  }
})

app.controller('View2Ctrl', function($scope, $stateParams, $state) {

  $state.go('app.view1', {view2Data: {varView2: 'varView2 Value' } });

)}

The problem is: If $stateParams vars are coded in in VIEW1 controller, this will create $stateParams vars undefined problem in case VIEW1 is accessed directly.

I'm thinking of something in VIEW1 controller like if SET ($scope.varView1 = $stateParams.view2Data.varView2;){ continue } .

Any solutions for this?


Solution

  • The state config params object lets you set default values so you should probably use something like

    params: {
        view2Data: {
            varView2: null
        }
    }
    

    At least then, you won't get an "undefined is not an object" error for $stateParams.view2Data.varView2.