Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
1  
Another approach would be to create a service that holds the data and inject the service into both controllers - have a look at stackoverflow.com/questions/21919962/… –  glendaviesnz Aug 9 '14 at 7:59
    
Here is a working demo, without the mistake of using $watch in the controllers. stackoverflow.com/questions/21904174/… –  cheekybastard Aug 10 '14 at 1:31

1 Answer 1

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.