Abhishek
Abhishek

Reputation: 351

Fetching the controller's name

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

  1. Type 1: Here 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???
  2. Type 2: Here i am getting the value directiveCtrl as it is outside... Can anyone explain in detail please Thanks in advance

Upvotes: 0

Views: 65

Answers (1)

Mistalis
Mistalis

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. If name 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

Related Questions