如何访问指令 link 中的控制器功能?

How to access controller functions in directive link?

如何从指令 link 访问指令控制器函数?传递给 link 的波纹管控制器是空的,我想进入其中 show() hide() 函数。

我当前的指令:

app.directive('showLoading', function() {
  return {
    restrict: 'A',
    // require: 'ngModel',
    scope: {
      loading: '=showLoading'
    },
    controller: function($scope, $element) {
      return {
        show: function() {
          alert("show");
        },
        hide: function() {
          alert("hide");
        }
      };
    },
    link: function($scope, $element, $attrs, controller) {
      $scope.$watch('loading', function(bool) {
        if (bool) {
          controller.show();//undefined
        } else {
          controller.hide();
        }
      });
    }
  };
});

你的控制器函数内部有问题

这里的代码工作正常

app.directive('showLoading', function() {
  return {
    restrict: 'AE',
    // require: 'ngModel',
    scope: {
      loading: '=showLoading'
    },
    controller: function($scope, $element) {
        $scope.show = function() {
          alert("show");
        },
        $scope.hide = function() {
          alert("hide");
        }
    },
    link: function($scope, $element, $attrs) {
      $scope.$watch('loading', function(bool) {
        if (bool) {
          $scope.show();//undefined
        } else {
          $scope.hide();
        }
      });
    }
  };
});

在范围内发布可以工作,但不是最佳实践,因为它 "pollutes" 范围。与自己的控制器通信的正确方法是 require 它 - 然后它将作为参数提供给 link 函数,以及其他必需的指令。

另一个问题是如何在控制器上公开函数 - 这是通过使用 this.someFn 而不是通过返回对象来完成的。

app.directive('showLoading', function() {
  return {
    restrict: 'A',
    require: ['ngModel', 'showLoading'], // multiple "requires" for illustration
    scope: {
      loading: '=showLoading'
    },
    controller: function($scope, $element) {
      this.show = function() {
        alert("show");
      };

      this.hide = function() {
        alert("hide");
      };
    },
    link: function($scope, $element, $attrs, ctrls) {
      var ngModel = ctrls[0], me = ctrls[1];

      $scope.$watch('loading', function(bool) {
        if (bool) {
          me.show();
        } else {
          me.hide();
        }
      });
    }
  };
});