DawnPaladin DawnPaladin - 1 year ago 82
AngularJS Question

Clearing a text entry field after processing the input

Having completed CodeSchool's AngularJS course, I'm trying to go back through and use what I've learned to build a simple to-do app. I've gotten it to the point where I can add entries to a list, but I'm not able to clear the text entry field after I've used the input. Here's my JSFiddle.

Specifically, here's my


card.addComment = function(newComment) {
newComment = {text: ""};

And the corresponding Angular HTML:

<form ng-submit="card.addComment(newComment)">
<input name="comment" placeholder="Add comment" ng-model="newComment.text">

At first I was passing the data in as a string (
<input ng-model="newComment">
instead of
), but then I remembered that strings get passed by value, not by reference. I figured
was being blanked in the function but not passed back through Angular to the document. But even after I changed
to an object so it would be passed by reference, it made no difference--clearing the value in JavaScript has no effect on the page. What am I doing wrong?

Answer Source

Try this:

card.addComment = function(newComment) {
  newComment.text = "";

What you're doing is creating a new object on the scope and breaking the binding which was set up on the original object. By updating the text property only, you leave the binding intact and achieve your goal of clearing the input field to which it is bound.