Reputation: 351
var app = angular.module('app', [])
app.controller('MainController', function MainController() {})
app.controller('directiveCtrl', function directiveCtrl() {})
.directive('controllerName', function($timeout) {
return {
restrict: 'A',
template: '<div>My controller name is: {{cName}}</div>',
controller: 'directiveCtrl',
link: function($scope, elem, attrs) {
var name;
console.log("printing");
name = elem.controller().constructor.name;
$scope.cName = name;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<div ng-app="app" class="container">
<div id="target" ng-controller="MainController">
<div>Type1</div>
<div controller-name></div>
</div>
***************************************************
<div id="target" ng-controller="MainController">
<div ng-controller="directiveCtrl">Type2
<div controller-name></div>
</div>
</div>
<hr/>
</div>
Hello,here i am trying get the name of the controller by using directive
controller-name
is having one parent controller named MainController
and it's own controller defined inside the directive with name directiveCtrl
...but when i try to access the controller name i am getting the name as MainController
not directiveCtrl
...why???Upvotes: 0
Views: 65
Reputation: 18279
From the docs of element.controller()
:
controller(name)
- retrieves the controller of the current element or its parent. By default retrieves controller associated with the ngController directive. Ifname
is provided as camelCase directive name, then the controller for this directive will be retrieved (e.g.'ngModel'
).
The function gets the parent controller defined with ng-controller
. This is a normal behavior, as you defined in Type 1:
<div ... ng-controller="MainController">
...
</div>
And in Type 2:
<div ...
<div ng-controller="directiveCtrl">
...
</div>
</div>
Upvotes: 1