使用回车键,ng-submit无法正常工作

时间:2015-01-14 17:29:20

标签: angularjs

我是AngularJS的新手,现在面临以下问题。

单击“提交”按钮可以很好地插入新项目,但是当我按下Enter按钮时不能正常工作。输入$ scope.newQueryInput是未定义的。

同样在第一次输入时,我会插入一个新项目(带有空字符串)。第二次击中没有任何事情发生,这也应该是第一击的预期行为。

<!--HTML part-->
<ul ng-controller="QueryCtrl">
    <li ng-repeat="query in queries">
        <i class="fa fa-trash onhover alignleft" title="delete query" ng-click="removeQuery($index)"></i>
        <a href="#">{{query.keyword}}</a>
    </li>
    <li class="addnew">
        <form ng-submit="addQuery()" action="">
            <input type="text" ng-model="newQueryInput" placeholder="Add new query"/>
            <input type="submit" />
        </form>
    </li>
</ul>


// script.js
var App = angular.module('App', []);
function QueryCtrl($scope) {
    $scope.queries = queries;
    $scope.addQuery = function() {
        console.log($scope.newQueryInput);
        console.log($scope);

        if (typeof $scope.newQueryInput != "undefined") {
            newQuery = { "keyword" : $scope.newQueryInput }
            $scope.queries.push(newQuery);
            $scope.newQueryInput = "";
        }
    };
    $scope.removeQuery = function(index) {
        $scope.queries.splice(index, 1);
    }
};

1 个答案:

答案 0 :(得分:1)

我已对您的表单进行了3次修复:

  1. $scope.queries = queries;更改为$scope.queries = [];,因为查询未定义

  2. 添加了$ event.preventDefault();提交处理程序,以便不提交表格。

  3. 添加了空字符串检查$ scope.newQueryInput!==“”

  4. 现在可以使用Enter键或按钮点击。

    <!doctype html>
    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
        </head>
        <body ng-app="plunker">
            <ul ng-controller="QueryCtrl">
                <li ng-repeat="query in queries">
                    <i class="fa fa-trash onhover alignleft" title="delete query" ng-click="removeQuery($index)"></i>
                    <a href="#">{{query.keyword}}</a>
                </li>
                <li class="addnew">
                    <form ng-submit="addQuery($event)" action="">
                        <input type="text" ng-model="newQueryInput" placeholder="Add new query"/>
                        <input type="submit" />
                    </form>
                </li>
            </ul>
        </body>
        <script>
        var app = angular.module('plunker', []).controller('QueryCtrl', ['$scope', function($scope) {
            $scope.queries = [];
            
            $scope.addQuery = function($event) {
                $event.preventDefault();
    
                if (typeof $scope.newQueryInput != "undefined"
                    && $scope.newQueryInput !== "") {
                    newQuery = { "keyword" : $scope.newQueryInput }
                    $scope.queries.push(newQuery);
                    $scope.newQueryInput = "";
                }
            };
            
            $scope.removeQuery = function(index) {
                $scope.queries.splice(index, 1);
            }
        }]);
        </script>
    </html>