javascript - 调用与 Angular 指令绑定(bind)的参数化函数

标签 javascript angularjs angularjs-directive

我创建了一个 Angular Directive(指令)来调用父 Controller 中接受参数的方法(true/false) 在我的父 Controller 中有一个方法

   app.controller('MyCtrl', function($scope){ 

     $scope.myMethod = function(val) {
       alert(val)

     };
});

在我的指令中

app.directive('confirmBox',function() {
    return {
        restrict: 'E',
        template: '<div>' +

            '<button ng-click="controlfunc(true)">Yes</button>' + 
            '<button ng-click="controlfunc(false)">No</button>' + 
         '</div>',
        scope: {

            controlfunc: '&funcattribute',

        },
        controller: function($scope) {                  
        }
    };
});

html代码是

 <confirm-box  funcattribute="myMethod()" ></confirm-box>

当我点击按钮时,我得到“未定义”

PLUNKR

最佳答案

这是编写自定义指令时非常常见的任务,记住如何以及在何处定义参数名称以及工具如何调用回调总是有点棘手。来自 https://docs.angularjs.org/guide/directive

Often it's desirable to pass data from the isolate scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, the hideDialog function takes a message to display when the dialog is hidden. This is specified in the directive by calling close({message: 'closing for now'})

对于您的示例,您必须将参数表达式修改为

<confirm-box  funcattribute="myMethod(value)"></confirm-box>

并像这样调用回调:

<button ng-click="controlfunc({ value : true })">Yes</button>
<button ng-click="controlfunc({ value : false })">No</button>

http://jsfiddle.net/so8sfryv/1/

关于javascript - 调用与 Angular 指令绑定(bind)的参数化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34175143/

相关文章:

javascript - 正则表达式 - 排除括号和带特殊键的括号

javascript - 将 C 中请求的数据返回到 ajax(jquery) CGI

AngularJS 指令作为注释

javascript - 使用同一 Angular Directive(指令)的多个副本时,变量不能独立运行

javascript - 如何在facebook邀请API上获取受邀用户信息

javascript - 使用可变参数过滤事物

javascript - Angular UI Bootstrap 进度条 - 如何用表达式计算 "value"属性?

AngularJS - 在登录时存储基本身份验证

javascript - 在小数点 Angular ui 网格对齐数字

javascript - AngularJS 数字文本输入 : Directive vs. 功能