Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

fix(compile): assign controller return value to correct controller #12036

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/ng/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -1997,9 +1997,12 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
for (i in elementControllers) {
controller = elementControllers[i];
var controllerResult = controller();

if (controllerResult !== controller.instance) {
// If the controller constructor has a return value, overwrite the instance
// from setupControllers and update the element data
controller.instance = controllerResult;
$element.data('$' + directive.name + 'Controller', controllerResult);
$element.data('$' + i + 'Controller', controllerResult);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, maybe the comment could be a bit more clear --- we're overwriting stuff that was done in setupControllers() because the return value was different from the pre-allocated instance.

if (controller === controllerForBindings) {
// Remove and re-install bindToController bindings
thisLinkFn.$$destroyBindings();
Expand Down
35 changes: 35 additions & 0 deletions test/ng/compileSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4573,6 +4573,41 @@ describe('$compile', function() {
});


it('should correctly assign controller return values for multiple directives', function() {
var directiveController, otherDirectiveController;
module(function() {

directive('myDirective', function(log) {
return {
scope: true,
controller: function($scope) {
return directiveController = {
foo: 'bar'
};
}
};
});

directive('myOtherDirective', function(log) {
return {
controller: function($scope) {
return otherDirectiveController = {
baz: 'luh'
};
}
};
});

});

inject(function(log, $compile, $rootScope) {
element = $compile('<my-directive my-other-directive></my-directive>')($rootScope);
expect(element.data('$myDirectiveController')).toBe(directiveController);
expect(element.data('$myOtherDirectiveController')).toBe(otherDirectiveController);
});
});


it('should get required parent controller', function() {
module(function() {
directive('nested', function(log) {
Expand Down