我创建了一个 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>
当我点击按钮时,我得到“未定义”
最佳答案
这是编写自定义指令时非常常见的任务,记住如何以及在何处定义参数名称以及工具如何调用回调总是有点棘手。来自 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>
关于javascript - 调用与 Angular 指令绑定(bind)的参数化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34175143/