2

Below is my code for ng-click. I want the click event to happen only once. I was thinking of adding comparison operator at the end but not sure. Please help as I am new to angular js.

<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<p>Click the button to run a function:</p>
<button ng-click="myFunc()">OK</button>
<p>The button has been clicked {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
  $scope.count++;
};
}]);
</script>
</body>
</html>

3 Answers 3

4

change the button code to

<button ng-click="!count && myFunc()">OK</button>

since $scope.count is 0 at the beginning click will fire only once.

Sign up to request clarification or add additional context in comments.

Comments

0

 
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script> 
<div  ng-app="myApp" ng-controller="myCtrl">
<p>Click the button to run a function:</p>
<button ng-click="myFunc()">OK</button>
<p>The button has been clicked {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
  if( $scope.count == 1)
       return false;

   $scope.count++;
};
}]);
</script> 

Comments

0

 
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script> 
<div  ng-app="myApp" ng-controller="myCtrl">
<p>Click the button to run a function:</p>
  <button ng-click="count === 0 && myFunc()">OK</button>
<p>The button has been clicked {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
  $scope.count++;
};
}]);
</script> 

Or use ng-show for hide/show the button

<button ng-show="count === 0" ng-click="myFunc()">OK</button>

like

 
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script> 
<div  ng-app="myApp" ng-controller="myCtrl">
<p>Click the button to run a function:</p>
  <button ng-click="count = 0">Clear</button>
<button ng-show="count===0" ng-click="myFunc()">OK</button>

<p>The button has been clicked {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
  $scope.count++;
};
}]);
</script> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.