Search code examples
angularjsangular-ui-routerangularjs-components

Passing object to all components from parent state in UI-Router


I revisited AngularJS after a long. Pleased to see they've gone ahead with components. I am trying to make use of components in my project.

I have few child component states that require access to parent component state. Basically an object will be shared across all child states. I am unable to achieve that with components.

general overview of architecture

Here's how the structure looks like -

  {
    name: 'wizard',
    url: '/wizard',
    component: 'wizard',
    redirectTo: 'wizard.init'
  },
  {
    name: 'wizard.init',
    url: '/init',
    component: 'init'
  },
  {
    name: 'wizard.customize',
    url: '/customize',
    component: 'customize'
  },
  {
    name: 'wizard.finish',
    url: '/finish',
    component: 'finish'
  }

There is an object / variable called $ctrl.settings in wizard component which I want to be shared across all it's child states.

I tried doing something like this -

<div ui-view settings="settings">

And accessing them in child components like this -

(function(angular){
  var app = angular.module('app');

  app.component('init', {
    templateUrl:'Scripts/dist/views/modules/wizard/init.html',
    controller: WizInit,
    bindings : {
      'settings' : '='
    }
  });

  function WizInit(){
    var $ctrl = this;

    $ctrl.$onInit = function(){
      console.log("init Start Step");
      console.log($ctrl.WizInit);
      $ctrl.WizInit= "start";
    }        
  }    
})(window.angular);

But I get undefined in every state even though I have assigned it to some value in parent component /wizard.

How can I make it work with components and ui-router?


Solution

  • Never mind,

    Solved it on my own. I just had to add $ctrl in ui-view directive of parent component state..

    <div ui-view settings="$ctrl.settings">
    

    Drawback of working late. You are not productive enough sometimes.