0

运行书中的一个例子,AngularJS,为什么单击Reset按钮会导致警报,sorry, please get more customers.

我只希望alert在按下Fund my startup!按钮时发生。

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

1 回答 1

2

您需要防止默认按钮单击行为(即提交)

角度最明确的方式:

以下是一种方式。(您也可以为此创建一个指令。)

模板:

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

javascript:

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

一般html中有些隐含的方式:

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

这通过覆盖恰好是“提交”的按钮元素的类型属性来工作。

于 2013-05-31T02:41:26.630 回答