简体   繁体   中英

Accessing directive function from controller using $scope.$parent.$$childHead.functionName in AngularJS

I have created a directive.

angular.module('app')
  .directive('navtree', function (service) {

    return {
      restrict: 'A',
      scope: {},
      link: function (scope, el) {

        scope.loadNavtree = function(){
          service.data()
              .then(function (data) {
                 ///Do something
              });
        }

        scope.loadNavtree();

      }
    };
  });

from my controller I can access the method using

$scope.$parent.$$childHead.loadNavtree();

Though this is working, I feel that this is not the right approach. I want to understand what are the disadvantages of accessing function defined in directive from your controller like this.

I looked this link but I was not able to follow

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
   /// How to call takeTablet() available in directive from here?
});

    app.directive('focusin', function factory() {
      return {
        restrict: 'E',
        replace: true,
        template: '<div>A:{{internalControl}}</div>',
        scope: {
          control: '='
        },
        link      : function (scope, element, attrs) {

          scope.takeTablet = function() {
            alert('from directive');// 
          }
        }
      };
    });

this is not the correct approach because angular do not recommend to use its private variable to access to directive function so you need to get a good approach to do that here is an example to access the directive function from controller.

If you want to use isolated scopes you can pass a control object using bi-directional binding ('=') of a variable from the controller scope. In this way you can control also several instances of the same directive on a page.

plunkr

Controller/Directive:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.focusinControl = {
  };
});

app.directive('focusin', function factory() {
  return {
    restrict: 'E',
    replace: true,
    template: '<div>A:{{internalControl}}</div>',
    scope: {
      control: '='
    },
    link      : function (scope, element, attrs) {
      scope.internalControl = scope.control || {};
      scope.internalControl.takenTablets = 0;
      scope.internalControl.takeTablet = function() {
        scope.internalControl.takenTablets += 1;  
      }
    }
  };
});

HTML:

<button ng-click="focusinControl.takeTablet()">Call directive function</button>
<h4>In controller scope:</h4>
{{focusinControl}}
<h4>In directive scope:</h4>
<focusin control="focusinControl"></focusin>
<h4>Without control object:</h4>
<focusin></focusin>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM