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

Commit be038d1

Browse files
devversionkara
authored andcommitted
feat(compiler): pass $element to controller instantiation (#9516)
* Pass the `$element` local to the instantiated controller, as same as a normal Angular 1.x DDO. Closes #9507.
1 parent dab6e50 commit be038d1

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/core/services/compiler/compiler.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ function mdCompilerService($q, $templateRequest, $injector, $compile, $controlle
6161
* - `link` - `{function(scope)}`: A link function, which, when called, will compile
6262
* the element and instantiate the provided controller (if given).
6363
* - `locals` - `{object}`: The locals which will be passed into the controller once `link` is
64-
* called. If `bindToController` is true, they will be coppied to the ctrl instead
64+
* called. If `bindToController` is true, they will be copied to the ctrl instead
6565
* - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in.
6666
*/
6767
this.compile = function(options) {
@@ -112,12 +112,19 @@ function mdCompilerService($q, $templateRequest, $injector, $compile, $controlle
112112
link: function link(scope) {
113113
locals.$scope = scope;
114114

115-
//Instantiate controller if it exists, because we have scope
115+
// Instantiate controller if it exists, because we have scope
116116
if (controller) {
117-
var invokeCtrl = $controller(controller, locals, true, controllerAs);
117+
118+
var ctrlLocals = angular.extend(locals, {
119+
$element: element
120+
});
121+
122+
var invokeCtrl = $controller(controller, ctrlLocals, true, controllerAs);
123+
118124
if (bindToController) {
119125
angular.extend(invokeCtrl.instance, locals);
120126
}
127+
121128
var ctrl = invokeCtrl();
122129
//See angular-route source for this logic
123130
element.data('$ngControllerController', ctrl);

src/core/services/compiler/compiler.spec.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,22 @@ describe('$mdCompiler service', function() {
132132
expect(data.element.controller().injectedOne).toBe(1);
133133
}));
134134

135+
it('should instantiate the controller with $element as local', inject(function($rootScope) {
136+
var ctrlElement = null;
137+
138+
var data = compile({
139+
template: '<span>hello</span>',
140+
controller: function Ctrl($scope, $element) {
141+
ctrlElement = $element;
142+
}
143+
});
144+
145+
var scope = $rootScope.$new();
146+
data.link(scope);
147+
148+
expect(ctrlElement).toBe(data.element);
149+
}));
150+
135151
it('should compile with controllerAs', inject(function($rootScope) {
136152
var data = compile({
137153
template: '<span>hello</span>',

0 commit comments

Comments
 (0)