I have a question concerning the visibility of function beween controllers and directives. I have a controller and a directive. The directive looks like this way
(function() {
'use strict';
angular
.module('myproject.schedule')
.directive('dirname', dirname);
function dirname() {
var directive = {
restrict: 'A',
replace: true,
scope: {
currentDateScheduler: "=",
...
},
controller: DirnameController,
controllerAs: 'vm',
bindToController: true,
templateUrl: ... directive.html
My controller looks like this:
(function() {
'use strict';
angular
.module('myproject.schedule')
.controller('MyController', MyController);
...
In the directive.html file I have a ng-click which invoked functions of my controller - and this works fine.
Actually now I am not sure why? I thought that a directive has its own namespace and the functions of my controller is not visible in ... directive.html.
Thanks a lot your help!
Controller scope is available to any directive that appears as a child within the DOM element on which the controller is declared. E.g.
<div ng-controller="ctrl1">
<dirname></dirnam> <!-- this has access to ctrl1 scope -->
</div>
So if you were to use the directive within another controller it would have access to that controllers scope. This means that if the function doesn't exist in the controller that the directive declared under then the ng-click will do nothing.
In the directive you can declare a controller, anything declared in this controller will override the controller function of the same name within the directive. E.g.
angular.module('myApp',[])
.controller('myController',function($scope){
$scope.clickMe = function(){
alert('clicked from the controller');
}
})
.directive('dirname', function(){
return {
controller: function($scope){
$scope.clickMe = function(){ alert('clicked from directive'); };
},
};
});
controllers can also be nested. In this case the scope again has a top down effect, whereby a function defined in the top most controller is available to the dom elements enclosed in a child controller. Also if this child controller has the same function declared then these will override the functionality of the parent controller.
Hope this helps
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments