search

Home  >  Q&A  >  body text

angular.js - How to use ng-click in directive

    return {
        restrict: 'E',
        replace: true,
        scope: {
            cancelFunc: '&'
        },
        template: '<section class="part-load">'
        + '<p class="part-text">正在加载</p>'
        + '<p class="part-close border-left" ng-click="cancelFunc"></p>'
        + '</section>',
        link: function (scope, elem, attrs) {

        }
    }
}]);

As above, a command partload is defined, expecting the attribute value cancelFunc to be passed in, binding the ng-click event, html structure:

<partload cancel-func="stop()"></partload>
A

method is defined in the stop controller:

$scope.stop = function () {
            alert(1)
}

But it doesn’t trigger, why? How to solve it?

阿神阿神2756 days ago561

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-15 17:14:06

    Thanks for the invitation

    The address of the online example: https://plnkr.co/edit/LBb4dN7...
    The only difference from young-click="cancelFunc()"

    reply
    0
  • 迷茫

    迷茫2017-05-15 17:14:06

    Thanks for the invitation

    I also made an online example: https://embed.plnkr.co/SirYJd...

    Try this

    return {
            restrict: 'E',
            replace: true,
            scope: {
                cancelFunc: '&'
            },
            template: '<section class="part-load">'
            + '<p class="part-text">正在加载</p>'
            + '<p class="part-close border-left" ng-click="_cancelFunc()"></p>'
            + '</section>',
            link: function (scope, elem, attrs) {
                scope._cancelFunc = function(){
                    // 这里可以写一些指令内部逻辑
                    scope.cancelFunc({id: 1}); // { id : 1 } 传参
                }
            }
        }

    reply
    0
  • Cancelreply