2

I have an existing AngularJS route with data from an API that is injected into the page controller (PrimaryController) using a route resolve (myDependency) from ngRoute. I'm adding more functionality to this page that I'm encapsulating in a sub-controller with ng-controller="SubController as subController"

That SubController operates primarily on myDependency, and the PrimaryController also operates on it. I can think of three ways to pass the data to SubController, and I was wondering if there is a best practice for this.

  1. Put the object on $scope and access it in the nested controller as $scope.myDependency. I'm hesitant to do this because I associate $scope properties with data or methods that are used in the HTML, and this object isn't. But this also seems like the most typical way to access data from a parent controller. I could use controller as syntax to make the dependency between SubController and PrimaryController clearer, like $scope.primary.myDependency.
  2. Put the data in a shared 3rd party service like MyService.myDependency. I don't like this very much because this is the only scenario/route in which this service will be used in this way, and it seems like overkill.
  3. Access the data using $route.current.locals.myDependency. I like this because it makes it clear that SubController depends on data from the route. This controller will never be used outside of this context, so I'm not worried about this being too limiting.

I know ui-router has support for accessing resolve data in nested views, but we're using ngRoute.

Alex Ross
  • 3,729
  • 3
  • 26
  • 26
  • sorry, I did not read it. If you not are using angular-ui router, then it's ok using `ng-controller as controller` syntax. – levi Nov 10 '15 at 00:57
  • thanks for your 3rd suggestion. I did not know it and think it is the cleanest, – Franck Jun 15 '16 at 15:58

0 Answers0