使用$scope.$parent.$$childHead从控制器访问指令函数.AngularJS中的functionNa

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

本文关键字:函数 指令 AngularJS 中的 functionNa 访问 控制器 scope parent childHead 使用      更新时间:2023-09-26

我已经创建了一个指令。

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();
      }
    };
  });
在控制器中,我可以使用 访问方法
$scope.$parent.$$childHead.loadNavtree();

虽然这是工作,我觉得这不是正确的方法。我想了解像这样从控制器访问指令中定义的函数的缺点是什么。

我看了这个链接,但是我无法跟随

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');// 
          }
        }
      };
    });

这不是正确的方法,因为angular不建议使用它的私有变量来访问指令函数,所以你需要有一个好的方法来做到这一点,这里有一个从控制器访问指令函数的例子。

如果你想使用隔离作用域,你可以通过bi-directional绑定一个变量的('=')从控制器作用域传递一个控制对象。通过这种方式,你还可以在一个页面上控制同一指令的多个实例。

plunkr

控制器/指令:

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>