我发现很多从指令调用控制器函数的例子,但是找不到从指令模板调用它的例子。
我们说我已经有了这个HTML代码来打开模态指令
<button ng-click='toggleModal()'>Open</button>
<modal-dialog show='modalShown' confirm="confirmCtrl()">
<p>Modal Content Goes here<p>
</modal-dialog>
这是我的控制器,其函数confirmCtrl()我想调用:
myApp.controller('myController', function($scope){
$scope.modalShown = false;
$scope.toggleModal = function() {
$scope.modalShown = !$scope.modalShown;
};
$scope.confirmCtrl = function () {
alert('confirmed');
}
})
这是我的指示。我
.directive('modalDialog', function(){
return {
restrict: 'E',
scope: {
show: '=',
corfirm: '&'
},
replace: true,
transclude: true,
link: function(scope, element, attrs) {
scope.hideModal = function() {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div><button ng-click=""> Confirm </button></div></div>"
};
在我的模板中,我有一个按钮,我想在点击时调用confirmCtrl()函数,但是,无法掌握如何操作
这是一个工作小提琴http://jsfiddle.net/anao4nsw/
答案 0 :(得分:4)
您可以在指令中定义控制器,并将ng-click指令添加到模板中的“确认”按钮元素。
.directive('modalDialog', function(){
return {
controller: 'myController' //This line.
restrict: 'E',
scope: {
show: '=',
corfirm: '&'
},
replace: true,
transclude: true,
link: function(scope, element, attrs) {
scope.hideModal = function() {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'>
<div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div>
<button ng-click='confirmCtrl()'> Confirm </button></div></div>"
请注意在模板的最后一行添加ng-click ='confirmCtrl()'。
答案 1 :(得分:2)
你几乎完成了你所需要的。 &amp; -binding可以解决这个问题:它为隔离范围的属性分配一个函数,当调用该函数时,它执行属性中指定的表达式。因此,在您的模板中,您只需在ng-click中调用隔离范围的此函数:<button ng-click="confirm()"> Confirm </button>
。由于输入错误,它可能对你不起作用:你有coRfirm: '&'
而不是coNfirm: '&'
。
答案 2 :(得分:2)
你的指令看起来如此,这项工作非常好。测试它,只复制并替换当前的指令
app.directive('modalDialog', function(){
return {
restrict: 'E',
scope: {
show: '=',
confirm: '&'
},
replace: true,
transclude: true,
link: function(scope, element, attrs) {
scope.hideModal = function() {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div><button ng-click='confirm()'> OK </button></div></div>"
};
});