加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:28:19 所属栏目:安全 来源:网络整理
导读:我已经找到了很多从指令调用控制器函数的例子,但是找不到从指令模板调用它的例子. 假设我有这个HTML代码来打开模态指令 button ng-click='toggleModal()'Open/button modal-dialog show='modalShown' confirm="confirmCtrl()" pModal Content Goes herep /mo
我已经找到了很多从指令调用控制器函数的例子,但是找不到从指令模板调用它的例子.

假设我有这个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/

您可以在指令中定义控制器,并在模板中的按钮元素“确认”中添加ng-click指令.
.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()’.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读