8

Trying to clear the input box after Add is clicked, like the guy is doing in this tutorial.
I have recreated the error without using the API, with this short code.
You can also check out the Plunker.

HTML

<input ng-model="contact.name" type="text">
<button ng-click="Add()">Add</button>

<ul ng-repeat="contact in contactList">
    <li>{{ contact.name }}</li>
</ul>

JS

$scope.contactList = [
    {name: 'cris'}, {name: 'vlad'}
;]

$scope.Add = function() {
    $scope.contactList.push($scope.contact)
    $scope.contact = ""
}

It seems that i can add 1 item, but on the second i get this Error: enter image description here

1
  • Your code is working fine check this fiddle jsfiddle.net/ADukg/9418. Tell me the exact scenario of the problem. Commented Jan 24, 2017 at 18:40

2 Answers 2

20

You didn't clean your contact object the right way. In the Add() function, change:

$scope.contact = ""

To:

$scope.contact = {};

Forked Plunker

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

2 Comments

Thanks! I guess the problem was, I changing the contact Object type to a string?
@Cris Exactly. :)
2

You are setting the $scope.contact property to a string here:

$scope.contact = ""

In your template you are binding to contact.name here:

<input ng-model="contact.name" type="text" class="form-control">

a string does not have the property "name", hence the error. A fix would be to do this:

$scope.contact = { name: "" }

This creates a new object with the property "name" and an empty string as the value of that property.

1 Comment

yes, happened with me. conflicting names from ng-repeat and scope vars in controller. thanks

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.