0

I have this shopping list app built in Angularjs which works just fine. I can add and delete items from it. But my issue is that I want to allow the app to add new items into the table using (event.which = 13) meaning using the "Enter" key from keyboard. Basically when user is on the input text field and after typing an item and pressing ENTER I want the new item to be added in my table. I think I'm close to accomplish this , but usually user will need to do this: type a text in input field and then press ENTER and then click anywhere outside the table in order to add the new item, but that wouldnt be the right way to add a new item. Please someone help on and let me know what I'm doing wrong. Thanks a lot in advance.

CodePen: http://codepen.io/HenryGranados/pen/BjWZKP

Here's my code:

 $("#keypresser").keypress(function(e){
    var codigo = e.which;
    var item   = document.getElementById("keypresser").value;
    if(codigo == 13){

        $scope.addNewItem(item);
        console.log("Hello");
    }

});

2 Answers 2

1

Use ngKeypress

Html

<input ng-keypress="pressed($event,newItem)" placeholder = "Enter item here..."class="form-control" ng-model="newItem"/>

JS

  $scope.pressed = function($event,item) {
    if ($event.which === 13)
      {$scope.addNewItem(item);
      console.log("hello");}
  }

CODEPEN

N:B: Don't use jquery in controller. it's not a good practice.

Sign up to request clarification or add additional context in comments.

Comments

1

IMHO, you don't have to use jquery in controller. This is a bad practice. Despite of that, if you want to use your snippet, you have to add $scope.$apply() to force digest cycle

$("#keypresser").keypress(function(e){
var codigo = e.which;
var item   = document.getElementById("keypresser").value;
if(codigo == 13){

    $scope.addNewItem(item);
    $scope.$apply();
    console.log("Hello");
}

});

The main difference is this code force the digest cycle who has the responsabilty to update model using two way binding.

To avoid this problem, you can use ngKeyPress

I hope that helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.