从AngularJS中的指令模板调用控制器函数

Cle*_*ine 8 angularjs

我已经找到了很多从指令调用控制器函数的例子但是找不到从指令模板调用它的例子.

假设我有这个HTML代码来打开模态指令

        <button ng-click='toggleModal()'>Open</button>
        <modal-dialog show='modalShown' confirm="confirmCtrl()">
            <p>Modal Content Goes here<p>
        </modal-dialog>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器,带有一个函数confirmCtrl()我想调用:

myApp.controller('myController', function($scope){
 $scope.modalShown = false;
 $scope.toggleModal = function() {
  $scope.modalShown = !$scope.modalShown;
};
$scope.confirmCtrl = function () {
    alert('confirmed');
}
Run Code Online (Sandbox Code Playgroud)

})

这是我的指示.一世

.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>"
Run Code Online (Sandbox Code Playgroud)

};

在我的模板中,我有一个按钮,我想在点击时调用confirmCtrl()函数,但是,无法掌握如何做到这一点

这是一个工作小提琴http://jsfiddle.net/anao4nsw/

Lee*_*ley 5

您可以像这样在指令中定义控制器,并将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>"
Run Code Online (Sandbox Code Playgroud)

请注意,在模板的最后一行中添加了ng-click ='confirmCtrl()'。

  • 哇,这将创建您的控制器的另一个实例,请注意! (3认同)

tho*_*rn̈ 2

你几乎已经完成了你需要的事情。& 绑定起到了作用:它将一个函数分配给隔离范围的属性,并且该函数在调用时执行属性中指定的表达式。因此,在您的模板中,您只需在 ng-click: 中调用隔离范围的此函数即可<button ng-click="confirm()"> Confirm </button>。由于拼写错误,它可能对您不起作用:您有coRfirm: '&'而不是coNfirm: '&'.