分离按钮单击“行为”



通过本书中的一个例子,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>

你需要阻止默认的按钮点击行为(即提交)

在angular中最显式的方式:

以下是单向的。(你也可以为此目的创建一个指令。)

模板:

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

这是通过重写button元素的type属性来实现的正好是" submit "

最新更新