从外部调用指令控制器方法

Call directive controller methods from outside

我编写了一个提供选项卡功能的指令,我使用的是最新版本的 AngularJS (v1)。 在我的指令中,我有一个控制器将 api 暴露给子指令,范围在所有指令中都是隔离的:

父指令

scope: {},
controller: function($scope) {
   $scope.values = [];

   this.addValue = function(value) {
        $scope.values.push(value);
   }
}

关于 link 函数的子指令

scope: {},
transclude: true,
template: '<div ng-transclude></div>',
replace: true,
link: function(scope, element, attr, parentCtrl)
{
    parentCtrl.addValues('test')
}

在子指令中,我有一个带有自己控制器的自定义 html: 测试Ctrl

function TestCtrl($scope){
    var vm = this;
    ... other logic
}

实施

<parent>
   <child>
      <div ng-controller="TestCtrl as t">
          <button ng-click="addValues('new_test')"></button>
      </div>
   </child>
</parent>

我需要在点击我的按钮时调用 "addValues" 方法(内部指令控制器)。

如何组织代码来实现这个?

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

module.controller('root', function ($scope) {
    $scope.test = function () {
        console.log('i am clicked');
    }
});

module.component('child', {
    template: '<button type="button" data-ng-click="$ctrl.click()">Click me</button>',
    controller: myController,
    bindings: {
        onClick: '&'
    }
});

function myController() {
    var ctrl = this;
    ctrl.click = function () {
        this.onClick();
    }
}
<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
</head>
<body data-ng-app="app">

    <div data-ng-controller="root">
        <child data-on-click="test()"></child>
    </div>
</body>
</html>

这只是一个例子 Here 你可以阅读更多。 希望这有帮助。

阅读 angular 的最佳实践可能会有用 here