5

I'm using angular-ui ui-router for a web-app. I have a state/view configuration like this:

...
.state('parentState', {
    url:'/:id',
    views: {
        'main@parent': {
            controller: 'ParentMainCtrl',
        },
        'sub@parent': {
            controller: 'ParentSubCtrl',
        },
    },
})
...

Now, I need to share data between the two states, main and sub. One way is to add a resolve to parentState and inject the dependency into the controllers of the views, but then I won't be able to do a data-binding between the two views. I tried adding a data attribute to parentState, but seems the children views do not inherit it. What would be a way to do a two-way data binding between the sibling views inside this state?

TeknasVaruas
  • 1,480
  • 3
  • 15
  • 28
  • 1
    Another approach would be to create a service that holds the data and inject the service into both controllers - have a look at http://stackoverflow.com/questions/21919962/angular-share-data-between-controllers – glendaviesnz Aug 09 '14 at 07:59
  • Here is a working demo, without the mistake of using $watch in the controllers. http://stackoverflow.com/questions/21904174/two-views-in-one-angularui-router-state-sharing-scope/21924873#21924873 – cheekybastard Aug 10 '14 at 01:31

1 Answers1

4

In my opinion, view routers shouldn't be responsible for data.

You should create a service that contains your data and operations to modify that data, then inject that service into your two controllers.

The nice thing about this too is that if you wanted to share this data source with even more modules besides ParentMainCtrl and ParentSubCtrl, you could add the service as a dependency to those modules.

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

angular.module('myApp').factory('sharedService', ['$http',
  function($http) {
    return {
      data: {},

      // functions to get/set properties in data
    }
  }
]);

angular.module('myApp').controller('ParentMainCtrl', ['$scope', 'sharedService',
  function($scope, sharedService) {
    $scope.data = sharedService.data;
  }
]);

angular.module('myApp').controller('ParentSubCtrl', ['$scope', 'sharedService',
  function($scope, sharedService) {
    $scope.data = sharedService.data;
  }
]);

http://plnkr.co/edit/WHIWUQRJNAmhQQKKJDDl?p=preview

Cameron Wilby
  • 2,222
  • 1
  • 25
  • 35
  • What if a data is selected on a view, that needs to be passed to another view? Considering this solution the sharedService.data must be already available. – Anoop Thiruonam May 16 '16 at 10:27