Reputation: 143
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>
Upvotes: 2
Views: 2372
Reputation: 38663
<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>
Upvotes: 0
Reputation: 41387
<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>
Upvotes: 0
Reputation: 8632
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.
Upvotes: 4