1

I have this html:

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

<script type="text/ng-template" id="/a">
  // SomeHtml with Angular templates
</script>

<script type="text/ng-template" id="/b">
  // SomeHtml with Angular templates
</script>

And:

angular.module('ngView', [], function($routeProvider, $locationProvider) {
  $routeProvider.when('/a', {
    templateUrl: '/a',
    controller: MyCtrl
  });

  $routeProvider.when('/b', {
    templateUrl: '/b',
    controller: MyCtrl
  });
});

The controller "MyCtrl" has some bootstrap code that is invoked when the html is first loaded, this bootstrap code sets up some state that should be used by both "/a" and "/b" template. Templates "/a" and "/b" will present the data obtained during the bootstrap to render in different ways.

I'd like to not have a controller and still be able to access MyCtrl scope from my templates.

Jayr Motta
  • 718
  • 1
  • 8
  • 26
  • 2
    I do not understand this question. You have two routes that are controlled by the same controller, what is the problem? – akonsu Dec 28 '12 at 15:09

3 Answers3

2

I would remove the wrapping controller, and have my routes each have their own controller. If these controllers need shared data then I would add a dedicated object that holds these data to the controllers' dependency lists. Here is an example: https://stackoverflow.com/a/9407953/410102

Community
  • 1
  • 1
akonsu
  • 28,824
  • 33
  • 119
  • 194
  • That sounds nice, but there is a way to set the life time of a dependency? Likewise in other DI containers I'd like to set a component to be application scoped and the like, thus I'd be able to bootstrap it at the right time and inject it to use the obtained data. – Jayr Motta Dec 28 '12 at 20:02
  • 1
    services are singletons in angularjs as far as I know. I would define a service that holds shared data and use it. – akonsu Dec 28 '12 at 20:05
1

Beside the Angular website says that you should point some controller you are not required to do it, and if the tag with the ng-view attribute is wrapped into another tag that has a ng-controller then the template rendered will be able to access the parent scope as usual.

Jayr Motta
  • 718
  • 1
  • 8
  • 26
0

Your template controller will have a parent controller (your so called wrapping controller), which it inherits. So you can execute functions and access properties from your wrapping controller.

function TemplateAController($scope) {
 ...
}

function WrappingController($scope) {
   $scope.execute = function() {
      ...
   }
    ...
   }

In your template:

<a ng-click="execute()">Execute</a>
asgoth
  • 35,552
  • 12
  • 89
  • 98