0

If I instantiate controller in html file I can initialize it using ng-init:

<div ng-controller="MyCtrl" ng-init="init()">

How can I initialize controller specified in $routeProvider?

$routeProvider.
    when('/structDefinedKeyValue', {
        templateUrl: 'app/partials/myTemplate.htm',
        controller: 'MyCtrl'

Thanks.

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
jazzblue
  • 2,411
  • 4
  • 38
  • 63
  • Just to say, using `$stateProvider` from `'ui.router'` would make your life a whole lot easier. – Joe Lloyd Sep 16 '15 at 21:50
  • 1
    Doesn't this answer your question? http://stackoverflow.com/questions/16150289/running-angularjs-initialization-code-when-view-is-loaded – Asa Sep 16 '15 at 21:51

1 Answers1

0

The router will instantiate the controller when loading the state. If you need some initialization work, you could call your init function inside the controller:

app.controller('MyCtrl', function () {

    // ...

    init();
}
Michel
  • 26,600
  • 6
  • 64
  • 69
  • Thanks, I need to call it from outside with a parameter,as I will have different instances of the same controller code. How could I achieve that? – jazzblue Sep 16 '15 at 21:52
  • Looks to me that you need state/route parameters. As you are using ngRoute, I guess you can have a look to [$routeProvider documentation](https://docs.angularjs.org/api/ngRoute/provider/$routeProvider) and inject `$routeParams` in your controller. – Michel Sep 16 '15 at 22:10