我编写了一个提供选项卡功能的指令,我使用了最新版本的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')
}在子指令中,我有一个带有自己的控制器的自定义html:TestCtrl
function TestCtrl($scope){
var vm = this;
... other logic
}Implementation
<parent>
<child>
<div ng-controller="TestCtrl as t">
<button ng-click="addValues('new_test')"></button>
</div>
</child>
</parent>我需要调用"addValues“方法(内部指令控制器)点击我的按钮。
如何组织代码来制作这个?
发布于 2017-11-09 12:15:36
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>
这只是一个例子,你可以读更多的这里。希望这能有所帮助。
MAy虽然它将是有用的阅读关于角角的最佳实践这里
https://stackoverflow.com/questions/47200049
复制相似问题