如何在指令链接中访问控制器功能?

luz*_*zny 9 javascript angularjs angularjs-directive angularjs-scope

如何从指令链接访问指令控制器功能?传递给链接的Bellow控制器是空的,我想在其中获取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();
        }
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

New*_*Dev 30

在范围上发布可以起作用,但不是最佳实践,因为它"污染"了范围.与自己的控制器进行通信的正确方法是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();
        }
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)