时间:2017-11-09 10:57:27

标签: javascript angularjs directive

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

家长指令

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

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

关于链接功能的子指令

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

在child指令中,我有一个带有自己控制器的自定义html: 的 TestCtrl

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”方法(在指令控制器内)。

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

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
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();
    }
}
&#13;
<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>
&#13;
&#13;
&#13;

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

关于角度的最佳实践here

,这将是有用的。