Search code examples
javascripthtmlangularjsdom-eventsevent-driven

ng-keypress to call function in angularjs


I have send button and I click on that button I send text from input. I want also on enter keyboard to send that text. I try with two solutions and nothing..

You can find my code below:

First Solution

<div class="modal-footer">
                <input id="enterText" name="enterText" class="form-control" aria-describedby="basic-addon1"
                       ng-model="modalInstanceController.showText" ng-keypress="keyEnter($event)">
                <br/>
                <button class="btn btn-primary" type="button" ng-click="modalInstanceController.concatConversation()"
                        ng-keypress="$event.which === 13 && modalInstanceController.concatConversation()">Send
                </button>
        </div>

Second solution

With send button I call this function:

 $scope.modalInstanceController.concatConversation = function () {

            $scope.modalInstanceController.currentConversation.push({
                loggedUser: $scope.modalInstanceController.showText,
                user: 'typing...'
            });
            $scope.modalInstanceController.showText = "";

        };

I also try to call this function in keyEnter function:

$scope.modalInstanceController.keyEnter = function (keyEvent) {
            if (keyEvent.which === 13) {
                $scope.modalInstanceController.currentConversation.push({
                    loggedUser: $scope.modalInstanceController.showText,
                    user: 'typing...'
                });
                $scope.modalInstanceController.showText = "";
            }
        };

$scope.modalInstanceController.keyEnter();

And in html:

<button class="btn btn-primary" type="button" ng-click="modalInstanceController.concatConversation()"
                        ng-keypress="modalInstanceController.keyEnter($event)">Send
                </button>

I am getting error:

TypeError: Cannot read property 'which' of undefined

Should I add something on dependency or what?


Solution

  • you can try

    if (keyEvent.keyCode === 13) 
    

    and one more thing

    <button class="btn btn-primary" type="button" ng-click="modalInstanceController.concatConversation()"
                            ng-keypress="$event.keyCode === 13 && modalInstanceController.concatConversation?modalInstanceController.concatConversation():''">Send
                </button>