我已经找到了很多从指令调用控制器函数的例子,但是找不到从指令模板调用它的例子.
<button ng-click='toggleModal()'>Open</button> <modal-dialog show='modalShown' confirm="confirmCtrl()"> <p>Modal Content Goes here<p> </modal-dialog>
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/
您可以在指令中定义控制器,并在模板中的按钮元素“确认”中添加ng-click指令.
原文链接:https://www.f2er.com/angularjs/142092.html.directive('modalDialog',function(){ return { controller: 'myController' //This line. restrict: 'E',scope: { show: '=',corfirm: '&' },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()’.