gpt4 book ai didi

javascript - AngularJS:需要来自子指令的父指令

转载 作者:行者123 更新时间:2023-11-29 19:22:21 25 4
gpt4 key购买 nike

请考虑这个Plunk .

我正在尝试为复杂指令访问设置一个测试用例,但我在从父指令调用方法时遇到错误:

父指令

app.directive('topParentDirective', [
'$compile',
function($compile){
return {
restrict: 'E',
transclude: true,
template: '<h3>I\'m the parent directive.</h3><div ng-transclude></div>',
controller: function($scope) {
$scope.ActivateMe = function(callerName) {
alert('Parent activated from caller ' + callerName);
};
}
};
}
]);

子指令

app.directive('interactingChildDirective', [
'$compile',
function($compile){
return {
scope: {
name: '@'
},
restrict: 'E',
require: ['^topParentDirective'],
templateUrl: 'interactingChildDirective.html',
link: function($scope, $elem, $attrs, $ctrl) {
var self = {};

console.log($ctrl);

$scope.CallTopParent = function() {
$ctrl.ActivateMe($attrs.name);
};
}
};
}
]);

InteractingChildDirective.html

包含:

My name is {{name}}, <button ng-click="CallTopParent()">Click me</button>!

HTML

<body ng-app="ngApp">
<div ng-controller="myController">
<top-parent-directive>
<interacting-child-directive name="Child 1"></interacting-child-directive>
</top-parent-directive>
</div>
</body>

问题

TypeError: $ctrl.ActivateMe is not a function
at n.$scope.CallTopParent

之所以如此,是因为 $ctrl 似乎不正确。

我该如何解决这个问题?这可能是一件非常简单的事情......

最佳答案

应该是

    controller: function($scope) {
this.ActivateMe = function(callerName) {
alert('Parent activated from caller ' + callerName);
};
}

因为 $ctrl 获取了所需 Controller 的 this

关于javascript - AngularJS:需要来自子指令的父指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32587713/

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