I know that a $scope
from a controller
can be shared to a link function in directives
.
For example, in this code I can call a function from declared controller to print 'Hello World' on browser console:
.directive('myDirective', [function () {
return {
restrict : 'E',
replace : true,
controller: 'MyController',
templateUrl : 'directives/myDirective.tpl.html',
link : function (scope, elem, attrs, controller) {
scope.message = 'Hello World!';
}
};
}])
.controller('MyController', [function ($scope, $element, $attrs, $log, $timeout) {
// $timeout to wait the link function to be ready.
$timeout(function () {
// This prints Hello World as expected.
$log.debug($scope.message);
});
});
}])
Ok, this works fine.
My questions are:
- In this approach, it is the SAME scope that will shared between the controller and the directive?
- What is the consequences to use this approach? Let us assume that I will not manipulate
DOM
elements in controller
, only in link function
.
- I really need to avoid manipulate DOM elements in this
controller
? Even if the $scope
, $elem
, etc are the same?
These are questions that I didn't find on Angular Directive documentation.
Here's a plunker with the sample code.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…