Search code examples
javascriptangularjsform-submitenter

How to submit a form with "Enter" in AngularJS?


I have a search form without a submit button. How can I route to #!/result, by pressing the enter key?

HTML:

<form ng-controller="searchCtrl">
   <input ng-href='#!/result' type="text"  placeholder="Поиск">
</form>

JS:

App.config(['$routeProvider',function($routeProvider){
        $routeProvider
            .when('/result',{
                templateUrl:'../views/result.html',
                controller:"searchCtrl",})  
}]);

Solution

  • To submit a form with ENTER you need a submit button. If you don't want one, a tricky way would be adding an invisible button in the form:

    <form ng-submit="redirect()">
        ...
        <input type="submit" style="visibility: hidden"/>
    </form>
    

    Note that I added a ng-submit call in the form:

    $scope.redirect = function() {
        $location.href('/result');
    }
    

    Here is a Plunker demo