【发布时间】:2015-08-13 21:56:26
【问题描述】:
我有一个与Box file picker 交互的指令。我的指令被 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>
回调函数在控制器内部被调用,但参数 是未定义的。
我可以通过使用“=”而不是“&”来解决这个问题,但我想知道为什么它不能使用“&”,因为它应该用于method binding
【问题讨论】:
标签: javascript angularjs angularjs-directive