DawnPaladin DawnPaladin - 6 months ago 18
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

addComment()
function:

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


And the corresponding Angular HTML:

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


At first I was passing the data in as a string (
<input ng-model="newComment">
instead of
newComment.text
), but then I remembered that strings get passed by value, not by reference. I figured
newComment
was being blanked in the function but not passed back through Angular to the document. But even after I changed
newComment
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

Try this:

card.addComment = function(newComment) {
  card.comments.push(newComment.text);
  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.