2013-05-31 74 views
0

通過本書中的示例AngularJS,爲什麼點擊Reset按鈕會導致警報sorry, please get more customers.分離按鈕單擊行爲

我只希望在按下Fund my startup!按鈕時發生alert

<html ng-app> 
<body> 

    <script src= 
"https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"> 
     </script> 

    <form ng-submit="requestFunding()" ng-controller="StartUpController"> 
     Starting: <input ng-change="computeNeeded()" ng-model="startingEstimate"> 
     Recommendation: {{needed}} 
     <button>Fund my startup!</button> 
     <button ng-click="reset()">Reset</button> 
    </form> 

    <script> 
     function StartUpController($scope) { 
      $scope.computeNeeded = function() { 
       $scope.needed= $scope.startingEstimate * 10; 
      }; 

      $scope.requestFunding = function() { 
       window.alert("sorry, please get more customers."); 
      }; 

      $scope.reset = function() { 
       $scope.startingEstimate = 0; 
      }; 
     } 
    </script> 
</body> 
</html> 

回答

2

您需要防止默認按鈕在角上單擊行爲(這是提交)

最明確的方式:

下面是一個方法。 (您可以創建用於此目的的指令,也。)

模板:

<button ng-click="reset($event)">Reset</button> 

的javascript:一般HTML

$scope.reset = function(event) { 
     event.preventDefault(); 
     $scope.startingEstimate = 0; 
    }; 

有些含蓄的方式:

<button type="button" ng-click="reset()">Reset</button> 

這通過重寫按鈕元素 的類型屬性來工作,這恰好是'提交'。

+0

爲什麼按鈕'submit'的默認行爲是調用'reset()'? –

+0

另一種方式:重置按鈕觸發提交,因爲任何按鈕的默認行爲都要提交。 – Tosh

+0

因此,除非我們使用'event.preventDefault()',否則所有按鈕(在控制器的範圍內?),即'submit',將導致調用reset() –