Angular TypeError: Unable to create property in string ''

Trying to clear the input field after clicking the "Add" button, as the guy does in this tutorial .
I updated the error without using the API with this short code.
You can also check out 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 element, but on the second I get this error: enter image description here

+5
source share
2 answers

You have not cleared your contact object in the correct way. In the Add() function, change:

 $scope.contact = "" 

To:

 $scope.contact = {}; 

Forked plunker

+10
source

You set the $ scope.contact property to a string:

 $scope.contact = "" 

In your template, you are attached to contact.name here:

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

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

 $scope.contact = { name: "" } 

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

+2
source

Source: https://habr.com/ru/post/1263268/


All Articles