2017-05-08 24 views
2

下面是我的ng-click代碼。我希望點擊事件只發生一次。我正在考慮在最後添加比較運算符,但不確定。請幫助,因爲我是新的角js。ng-click角度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

改變按鈕代碼

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

因爲$scope.count是0開頭的點擊就會觸發一次。

+0

感謝@Karim,它的工作! –

+0

不客氣;) – Karim

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>

+0

這個邏輯也奏效了,謝謝@sachila ranawaka! –

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>

或者使用ng-show用於隱藏/顯示按鈕

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


 
<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>