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

标签 javascript angularjs

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

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/

相关文章:

javascript - Angular 形式。设置类型选项

javascript - 从 md-tab 自定义未选择的 md-tab-label 的样式

javascript - IHttpPromise 使用 TypeScript 2.5 错误地扩展了 IPromise

javascript - AngularJS - 为什么在指令中使用匿名 Controller ?

javascript - 当值超过 100 时,如何使用 AngularJS 初始化输入[范围]的值

javascript - 向下滑动事件未触发 - ionic 框架

javascript - jQuery 日期选择器。 2 个日期选择器。限制范围 : Max date of 2 weeks from the selected start date

javascript - Service Worker 从缓存中获取请求,因此页面不会从新数据中更新

JavaScript 命名空间和 jQuery

angularjs - typescript :TS2496: 'arguments' 对象不能在 ES3 和 ES5 的箭头函数中引用。考虑使用标准函数表达式