gpt4 book ai didi

javascript - 指令父级单击中的 Angular Directive(指令)

转载 作者:行者123 更新时间:2023-12-01 03:16:27 27 4
gpt4 key购买 nike

我正在创建一个指令来显示文本差异。对于这个指令,我需要几个按钮,我将它们分成了指令。一个简单的例子是:

.directive('differenceViewer', function($templateCache, $compile) {
return {
restrict: 'E',
scope: {
oldtext: '@',
newtext: '@',
template: '@',
heading: '@',
options: '=',
itemdata: '&',
method: '&'
},
replace: false,
link: (scope, element, attr) => {
element.append(angular.element($compile($templateCache.get(scope.template))(scope)));
}
};
}).directive('diffbutton', function() {
return {
restrict: 'E',
scope: {
method: '&'
},
template: '<button class="btn btn-sm btn-success" ng-click="method()">Rollback</button>',
replace: true,
terminal: true,
link: (scope, element, attr) => {
scope.directiveClick = function(){
console.log("directive method"); // is never called
}

}
}
})

我通过模板脚本编译 html:

<script type="text/ng-template" id="differenceViewer.html">
<div class="ibox-footer">
<div class="row">
<div class="col-md-12">
<diffbutton method="clickedBtn()">Foo</diffbutton>
</div>
</div>
</div>
</script>

differenceViewer 编译的 html 中创建 diffbutton

我需要调用 Controller 中负责创建所有差异 View 的方法。

app.controller('MainCtrl', function($scope) {
$scope.clickedBtn = function() {
console.log('foo'); // is never called
}
})

Here's a plunker演示该问题。

我需要更改什么才能将指令中指令上的按钮点击转发到 Controller 方法?

我一直在研究 this question 的答案但仍然无法使其工作。

请注意,如果我添加

scope.clickedBtn = function() {console.log("bar");}

对于 differenceViewer 指令,它被调用 - 但是我需要调用 Controller 中的方法。

最佳答案

将方法从父元素传递到子元素,然后在单击时触发它。例如(伪代码传入)

<parent-directive>
<child-directive totrigger="parentClickCallback()"></child-directive>
</parent-directive>

然后在你的父指令中设置

$scope.parentClickCallback = function(){//do whatever you neeed}

以及您设置的范围绑定(bind)中的 child

scope:{
totrigger:'&'
}

在该子按钮上您只需添加

<button ng-click="totrigger()">ClickMe</button>

每次单击该按钮时,都会通过附加到trigger的引用触发parentClickCallback。

为什么你需要让你的代码变得如此复杂,我不太确定。如果您对范围绑定(bind)不满意,只需在指令中需要 Controller 并传递 Controller 绑定(bind)函数。

关于javascript - 指令父级单击中的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45506749/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com