Ghasem
Ghasem

Reputation: 15643

disable AngularJS ng-click in <a> tag

I can disable a button with ng-disabled in AngularJS.

<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
   Previous
</button>

But how can I do the same thing when I'm using <a> tag?

This is not working

<a ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
   Previous
</a>

Upvotes: 1

Views: 2477

Answers (1)

jValdron
jValdron

Reputation: 3418

An <a> tag doesn't have a disabled state. See here: http://www.w3schools.com/tags/tag_a.asp

So you'll have to have a condition that checks if the currentPage variable should be changed.

You could use ternary operators, which are available since Angular 1.1.5.

<a ng-click="currentPage = currentPage ? currentPage - 1 : 0">
   Previous
</a>

The condition is basically saying that currentPage should be 0 if currentPage is 0, if it's not 0, then currentPage - 1.

Do note that Angular is not keen on having control flow statements in your HTML, see No Control Flow Statements here https://docs.angularjs.org/guide/expression. You should instead create a function like so:

<a ng-click="prevPage();">
   Previous
</a>

And then define it in your controller:

$scope.prevPage = function(){
    if ($scope.currentPage > 0) $scope.currentPage = $scope.currentPage - 1;
};

Upvotes: 4

Related Questions