gpt4 book ai didi

javascript - AngularJS - 使用指令调用回调函数?

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

我无法弄清楚为什么我的指令没有从我的父页面调用我的回调函数。您能帮忙吗?

Angular 代码:

    angular
.module('myApp')
.directive('testDirective', function () {
return {
bindToController: {
foo: '@',
myCallback: '&'
},
controller: function () {
},
controllerAs: 'vm',
restrict: 'E',
replace: true,
scope: {},
template: '<div>Foo is: {{ vm.foo }} <button data-ng-click="vm.myCallback()">Click to call Callback</button></div>'
};
});

angular
.module('myApp')
.controller('ParentController', function () {
this.myParentCallback = function () {
alert('Called the parent callback function');
};
});

HTML 代码:

<body>
<div data-ng-app="myApp" data-ng-controller="ParentController as ctrl">
<test-directive foo="bar!" my-callback="ctrl.myParentCallBack"></test-directive>
</div>
</body>

如您所见,foo 绑定(bind)正确,但我无法让 myCallback 工作...

想法?

这是 plnkr 中的内容:( http://plnkr.co/edit/niVL5iAeOJ6XTpkpL9fu?p=preview )

最佳答案

这是一个大小写问题:在回调中传递 ctrl.myParentCallback 时使用小写 b。

此外,您的 plnkr 有一个错误,即 vm.myParentCallBack。替换为:

<test-directive foo="bar!" my-callback="ctrl.myParentCallback()"></test-directive>

http://plnkr.co/edit/VnMUekTSZyk5WagsPqkL

关于javascript - AngularJS - 使用指令调用回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040725/

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