我有一个这样设置的指令:
angular.module('widget.directives').directive('applePay', applePay);
function applePay() {
return {
restrict: 'A',
controller: 'ApplePayController',
controllerAs: 'controller',
scope: {
onCheckComplete: '&applePay'
},
bindToController: true,
templateUrl: 'app/directives/apple-pay/apple-pay.html',
link: function (scope, element, attrs, controller) {
element.find('button').bind('click', controller.checkout);
}
};
};
它的 Controller 如下所示:
angular.module('widget.directives').controller('ApplePayController', applePayController);
applePayController.$inject = ['applePayService'];
function applePayController(applePayService) {
var self = this;
// Method binding
self.checkout = checkout;
init();
//////////////////////////////////////////////////
function init() {
applePayService.checkAvailability(setAvailability);
};
function setAvailability(available) {
self.available = available === true;
console.log(self);
self.onCheckComplete({ available: self.available });
};
function checkout(e) {
applePayService.checkout(e, onComplete, onError);
};
function onComplete(result, completion) {
console.log(result, completion);
};
function onError(error) {
self.error = error;
};
};
我的 html 是这样的:
<div apple-pay="controller.applePayAvailable(available)"></div>
当指令加载时,我收到错误:
TypeError: self.onCheckComplete is not a function
有人知道为什么吗? 我有一个类似的指令,效果很好。
最佳答案
这是因为 Controller 有一个 init 方法,在实例化 Controller 时会调用该方法。问题在于范围尚未绑定(bind)。所以我必须将 Controller 更改为:
angular.module('widget.directives').controller('ApplePayController', applePayController);
applePayController.$inject = ['applePayService'];
function applePayController(applePayService) {
var self = this;
// Method binding
self.init = init;
self.checkout = checkout;
//////////////////////////////////////////////////
function init() {
applePayService.checkAvailability(setAvailability);
};
function setAvailability(available) {
self.available = available === true;
console.log(self);
self.onCheckComplete({ available: self.available });
};
function checkout(e) {
applePayService.checkout(e, onComplete, onError);
};
function onComplete(result, completion) {
console.log(result, completion);
};
function onError(error) {
self.error = error;
};
};
然后将 init 方法添加到指令上的链接函数中。
angular.module('widget.directives').directive('applePay', applePay);
function applePay() {
return {
restrict: 'A',
templateUrl: 'app/directives/apple-pay/apple-pay.html',
controller: 'ApplePayController',
controllerAs: 'controller',
bindToController: true,
scope: {
onCheckComplete: '&applePay'
},
link: function (scope, element, attrs, controller) {
element.find('button').bind('click', controller.checkout);
controller.init();
}
};
};
与上面的唯一区别是将 init 方法添加为 Controller 上的公共(public)方法,然后从指令中调用 controller.init()
。这确保了范围在启动之前被绑定(bind)。
关于javascript - angularjs bindToController无法调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44204476/