![](/img/trans.png)
[英]Angular directive passing arguments to controller function within element's .html()
[英]Angular Directive bind function with & not passing arguments to controller
我有一个与Box文件选择器交互的指令。 我的指令由2个独立的控制器使用,可能在将来增加更多。
Box文件选择器允许您在用户选择文件/文件夹后设置回调函数,如下所示:
var boxSelect = new BoxSelect();
// Register a success callback handler
boxSelect.success(function(response) {
console.log(response);
});
我的控制器正在使用该指令,它们将成功的回调逻辑作为范围变量,我将其传递给指令。
我创建了一个plunkr ,我在嘲笑Box选择行为
调节器
.controller('myController', function($scope) {
$scope.onSuccessful = function(message) {
alert('Success! Message: ' + message);
};
})
指示
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.onSuccessful = function(message) {
//message is undefined here
alert('Success! Message: ' + message);
};
})
.directive('myDirective', function() {
return {
restrict: 'A',
scope: {
success: '&'
},
link: function(scope, element) {
//third party allows to subscribe to success and failure functions
function ThirdPartySelect() {
}
ThirdPartySelect.prototype.success = function(callback) {
this.callback = callback;
};
ThirdPartySelect.prototype.fireSuccess = function() {
this.callback({
foo: 'bar'
});
};
var myThirdPartyInstance = new ThirdPartySelect();
myThirdPartyInstance.success(function(message) {
//message is still defined here, but not in the controller
scope.success(message);
});
element.on('click', function() {
myThirdPartyInstance.fireSuccess();
});
}
};
});
视图
<div ng-controller="myController">
<button my-directive success="onSuccessful(arg)">Test</button>
</div>
回调函数在控制器内部被调用,但参数未定义。
我能够通过使用'='代替'&'来解决这个问题,但我想知道为什么它不能与'&'一起工作,因为它应该用于方法绑定
是的,要将控制器函数绑定到指令,必须使用&
bindings(表达式绑定),它允许指令调用由DOM属性定义的表达式或函数。
但是在您的指令中,当您调用绑定方法时,函数参数应该是一个对象,其中键与您在控制器中声明的参数相同,当您定义函数时。
所以在你的指令中,你必须替换:
scope.success(message);
通过:
scope.success({message:message.foo});
然后在您的HTML中,您必须替换:
<button my-directive success="onSuccessful(arg)">Test</button>
通过:
<button my-directive success="onSuccessful(message)">Test</button>
你可以看到Working Plunker
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.