我在将函数传递给指令时遇到了问题(这篇文章很熟悉:AngularJS - pass function to directive,但我无法让它工作)
这是我的代码:
指令:
.directive('testdirective', function(){
return{
restrict: 'E',
scope: {
onClick: '&'
},
controller: 'TestController',
controllerAs: 'tc',
bindToController: true,
template: '<div><button ng-click="onClick()">What UP</button></div>',
replace: true
}
})
Controller :
TestController.$inject = ["$scope"];
function TestController($scope) {
$scope.testFunction = function(){
alert("I´m the alert of the TestContoller");
};
$scope.test = 'test';
}
HTML:
<div>
<testdirective on-click="testFunction()"></testdirective>
</div>
我想要的听起来很简单,我只想将函数传递给指令并通过 ng-click 按钮执行它。
对我来说,我的代码看起来完全一样 like this fiddle 但我的不工作:/
如果有人给我一些提示,那就太好了。
编辑
My directive will need his own controller !
Later the function to be passed in will come from another controller !!!
最佳答案
fiddle 与您的代码不一样。
您已将指令的 Controller 设置为“TestController”。我假设您想做的是:
.directive('testdirective', function(){
return{
restrict: 'E',
scope: {
onClick: '&'
},
template: '<div><button ng-click="onClick()">What UP</button></div>',
replace: true
}
});
并在您的 HTML 中,
<div ng-controller="TestController">
<testdirective on-click="testFunction()"></testdirective>
</div>
编辑:基于OP的评论
app.directive('testdirective', function(){
return{
restrict: 'E',
scope: {
onClick: '&'
},
template: '<div><button ng-click="tc.onClick()">What UP</button></div>',
replace: true,
controller: 'TestController',
controllerAs: 'tc',
bindToController: true
}
});
app.controller('TestController', function ($scope) {
console.log($scope);
}) ;
app.controller('AnotherController', function ($scope) {
$scope.testFunction = function(){
alert("I´m the alert of the TestContoller");
};
$scope.test = 'test';
});
还有,你的 HTML
<div ng-controller="AnotherController">
<testdirective on-click="testFunction()"></testdirective>
</div>
您正在将指令告诉bindToController。因此,在指令的模板中,onClick 绑定(bind)到 Controller 而不是范围。因此,您可以通过 Controller 作为指令模板中的 tc.onClick()
访问 onclick。
关于javascript - AngularJS:将函数传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34991060/