Injecting a controller that's part of a module

994 views
Skip to first unread message

Andrew Walker

unread,
Apr 14, 2012, 4:09:44 PM4/14/12
to AngularJS
I would like to take my controllers out of the global scope and assign
them to modules. It would seem I should be doing this like so

angular.module
(
'myApp.controllers',
[]
)
.controller
(
'MyCtrl1',
function($scope){}
);

But now I am not sure how to inject MyCtrl1 for unit testing (or
anywhere really).

For some cases I am able to reference the controllers as strings e.g.

angular.module
(
'myApp.routes',
[]
).
config
(
[
'$routeProvider',
function($routeProvider)
{
$routeProvider.when('/view1', {template: 'partials/partial1.html',
controller: 'MyCtrl1'});
$routeProvider.when('/view2', {template: 'partials/partial2.html',
controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}
]
);

But I don't understand how this works. I got the idea from here
http://groups.google.com/group/angular/browse_thread/thread/7fac272694f84fc0/2f80ebf3f2c01621?lnk=gst&q=inject+controller#2f80ebf3f2c01621

Here is an attempted unit test using inject in the 'beforeEach'
http://jsfiddle.net/woxorz/T86hy/7/

Here is an attempted unit test using inject in the 'it'
http://jsfiddle.net/woxorz/T86hy/8/

brenda...@gmail.com

unread,
Apr 14, 2012, 4:21:52 PM4/14/12
to ang...@googlegroups.com
I was just about to ask exactly the same question. I like the new module.controller function, but have no idea how to inject them for testing.

brenda...@gmail.com

unread,
Apr 14, 2012, 4:37:23 PM4/14/12
to ang...@googlegroups.com
I think I worked it out from the documentation here

under "Testing Controllers"

I have forked and updated your jsfiddle


Andrew Walker

unread,
Apr 14, 2012, 4:42:58 PM4/14/12
to AngularJS
Awesome! That's exactly what I was looking for. Thank you :)

On Apr 14, 1:37 pm, brendan.o...@gmail.com wrote:
> I think I worked it out from the documentation here
>
> http://docs-next.angularjs.org/guide/dev_guide.mvc.understanding_cont...
Reply all
Reply to author
Forward
0 new messages