简体   繁体   中英

AngularJS: prevent ng-click from being executed

This is a pseudo code of a Directive I'm modifying. Let's assume I have the following event handlers:

<a my-link ng-click="foo()" foo-check="fooCheck"></a>
angular.module('linkModule')
.directive('mylink', function () {

    return {
        restrict: 'A',
        scope: {
            fooCheck: '='
        },
        link: function link ($scope, $element) {

            // bar method has some vital function 
            // for this directive`s functionality and must be run 
            // ONLY if certain conditions are met.
            var bar = function bar () {
                console.log('Executing bar');
            };

            $element.on('click', function (e) {
                e.preventDefault();

                // Validate something here
                var mustContinue = $scope.fooCheck();

                if ( mustContinue ) { 
                    bar(); 
                } else {
                    // Cancel ng-click here
                }
            });
        }
    };
});

So, my question is: Can I prevent the ng-click event from being executed from the directive's link event listener?

Maybe something like this ?

HTML

<a my-link ng-click="foo" foo-check="fooCheck" text="Click me!"></a>

JavaScript

var myApp = angular.module('myApp',[])
    .directive('myLink',[function () {
        return {
            restrict: 'A',
            scope: {
                fooCheck: '=',
                ngClick: '=',
                text: '@'
            },
            template: '<div ng-click="click($event)">{{text}}</div>',
            controller: function ($scope) {
                var bar = function bar () {
                    console.log('Executing bar');
                };
                $scope.click = function(evt){
                    var mustContinue = $scope.fooCheck();
                    if (mustContinue) { 
                        bar();
                        $scope.ngClick();
                    }
                }
            }
        };
    }]);

myApp.controller("myController",["$scope", function($scope){
    $scope.fooCheck = function(){
        return true;   
    }
    $scope.foo = function(){
        console.log("Foo executed");   
    }
}]);

you can do a compare expression into your ng-click and check true or false with a flag. if it is true the ng-click will be active otherwise it is disabled.

example: if hasBackground = true the expand function is executed.

<i style="cursor: pointer" class="fa fa-expand fa-3x" ng-click="hasBackground || expand()"></i> 

hope helps good luck.

You can try if

e.stopPropagation()

works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM