Angular TypeError:无法在字符串''上创建属性

时间:2017-01-24 15:57:58

标签: angularjs

单击“添加”后尝试清除输入框,就像那个人在this tutorial中一样 我使用这个简短的代码重新创建了错误而没有使用API 您还可以查看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 = ""
}

似乎我可以添加1个项目,但在第二个我得到此错误: enter image description here

2 个答案:

答案 0 :(得分:14)

您没有以正确的方式清理contact个对象。在Add()函数中,更改:

$scope.contact = ""

要:

$scope.contact = {};

Forked Plunker

答案 1 :(得分:2)

您在此处将$ scope.contact属性设置为字符串:

$scope.contact = ""

在您的模板中,您绑定到contact.name:

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

字符串没有属性“name”,因此出错。修复就是这样做:

$scope.contact = { name: "" }

这将创建一个新对象,其属性为“name”,空字符串为该属性的值。