3

I have multiple nested views in Ui router. I want to know if it's possible for them all to share one controller for the some identical functionality, and then have their own controllers for other functionality. I'd like this parent controller to make a few api calls, and store some scope variables so I don't have to make these calls individually inside each controller. I know I can achieve something similar with a resolve, but is 2 controllers for one view possible?

heres an example of my code of what my code looks like

.state('app.user', {
  url: '/user',
  resolve: {
    userData: ["UserService", function(UserService) {
      return UserService.getuser().then(function(profile) {
        UserService.profile = profile.data;
        UserService.currentId  = profile.data.user.id;
        return profile.data;
      });
    }]
  },
  views: {
    'content@': {
      templateUrl: ENVApp + '/views/user/profile.html?',
      controller: 'UserController'
    },
    'addresses@app.user': {
      templateUrl: ENVApp + '/views/partials/addresses?',
      controller: 'UserAddressController'
    }
  }
})
Shamoon
  • 41,293
  • 91
  • 306
  • 570
ceckenrode
  • 4,543
  • 7
  • 28
  • 48

2 Answers2

3

Yes, I do this in most of my apps. On my body div I specify a controller named appController with ng-controller="appController as app" and then I can reference it from within any view in my application as app.

Mike Feltman
  • 5,160
  • 1
  • 17
  • 38
  • So say for example I use the parent controller in this way to do an api call and now I have data I'm going to be using in all of these nested views as a scope variable, how can I access that scope variable from within the view's dedicated controller? – ceckenrode May 12 '16 at 18:08
  • Yes. There's a great answer on the specifics of this here: http://stackoverflow.com/questions/21453697/angularjs-access-parent-scope-from-child-controller – Mike Feltman May 12 '16 at 18:15
0

you could just do

<div ng-controller="parentController">  
    <div ng-view></div>
</div>

parentController is the common controller for identical functionality and ng-view will be updated for individual controllers.

Wild Widow
  • 2,359
  • 3
  • 22
  • 34