Angular js指令使用控制器作为语法ng点击不起作用

Angular js directive using controller as syntax ng-click not working

本文关键字:ng 语法 不起作用 指令 js 控制器 Angular      更新时间:2023-09-26

我在Angular 1.3中使用"controller as"语法在具有隔离作用域的指令中获取点击事件时遇到问题。指令代码如下:

myDirectives.directive('gsphotosquare', dirfxn);
function dirfxn() {
    var directive = {
        replace: false,
        scope: {
            photoInfo: '=',
            photoBatchNum: '=',
            thumbnailwidth: '='
        },
        restrict: 'EA',
        controller: Ctrller,
        controllerAs: 'ctrl',
        template: '<div ng-click="ctrl.squareClicked()">test</div>',
        //templateUrl: 'views/directives/gsphotosquare.html',
        bindToController: true, // because the scope is isolated
        link: linkFunc //adding this didn't help
    };
    return directive;
}
function Ctrller() {
    var vm = this;
    vm.squareClicked = function () {
        alert('inside clickhandler for gsphotosquare directive');
    };
}
function linkFunc(scope, el, attr, ctrl) {
    el.bind('click', function () {
        alert('inside clickhandler for gsphotosquare directive');
    });
}

以下是该指令在DOM中的使用方式:

 <span class="input-label">General Site Photos</span>
    <div class=" item row">
    <gsphotosquare photo-info="mt.photos.v1f1[0]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
    <gsphotosquare photo-info="mt.photos.v1f1[1]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
    <gsphotosquare photo-info="mt.photos.v1f1[2]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
   <gsphotosquare photo-info="mt.photos.v1f1[3]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
</div>

你知道为什么点击呈现的指令不会显示警报吗?

尝试以不同的方式定义您的控制器:

myDirectives.controller('Ctrller', Ctrller);

然后在你的指令中:

controller: 'Ctrller as ctrl',