Disable ng-click in AngularJS

The job I am trying to solve is described blew:

When I click on a DOM element like a button or a link, it triggers an event. When I click again, it does nothing. In another word, I want to disable it or prevent it from any future clicks after first click.

I looked up Angular Doc and found ngDisabled. However, button disable is controlled by the checkbox in the example of documentation, which is not exactly what I am looking for.

Then I thought there was no native solution from AngularJS to diable ng-click. So I added my own trick here:

Trick 1: Demo

HTML:

<body ng-app="ngToggle">
    <div ng-controller="AppCtrl">
        <button ng-click="disableClick(1)">Disable ng-click</button>
    </div>
</body>

JS:

angular.module('ngToggle', [])
    .controller('AppCtrl',['$scope', function($scope){
    $scope.flag = 0;
    $scope.disableClick = function(n) {
        if (n && n !== $scope.flag) {
            $scope.flag = n;
            alert("Clicked!");
        }
        return false;
    }
}]);

I wasn't happy about my code. With a lot more experiments and tests, finally, I found the optimal solution for my problem, which uses native ngDisabled.

Trick 2: Demo

HTML:

<body ng-app="ngToggle">
    <div ng-controller="AppCtrl">
        <button ng-click="disableClick()" ng-disabled="isDisabled" ng-model="isDisabled">Disable ng-click</button>
    </div>
</body>

JS:

angular.module('ngToggle', [])
    .controller('AppCtrl',['$scope', function($scope){
    $scope.isDisabled = false;
    $scope.disableClick = function() {
        alert("Clicked!");
        $scope.isDisabled = true;
        return false;
    }
}]);

Yang Zhao

Read more posts by this author.


Comment