Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share data between two ui-views inside a state in angularjs ui-router

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?

like image 413
TeknasVaruas Avatar asked Oct 01 '22 02:10

TeknasVaruas


1 Answers

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

like image 125
Cameron Wilby Avatar answered Nov 03 '22 21:11

Cameron Wilby