Angularjs动态绑定ng-model

时间:2013-06-25 16:34:04

标签: angularjs

以下是描述我在Angularjs中动态绑定问题的Plunker。

http://plnkr.co/edit/fGgtOZ5IrJVo9QasQALc?p=preview

在使用Angularjs之前,我习惯使用输入名称/值,如下所示为后端处理生成所需的数据结构

<input type="text" name="computer[details][][purchaseddate]" />

<input type="text" name="computer[details][][warrantyperiod]" />

使用Angularjs ng-model,可以绑定复杂的数据结构,如

<input type="text" ng-model="computer.parts[0].name" />

但是它不适用于动态属性,如下所示:

<input type="text" ng-model="computer.details[0].name" />

Angular一直告诉我,我正在尝试将属性'name'设置为undefined'details [0]',我知道但是有什么方法可以获得与之前输入的名称/值相同的行为,我可以指定动态属性而不必先声明它?

谢谢,

2 个答案:

答案 0 :(得分:3)

绑定到不存在的属性仍然有效。即使$ scope.a不存在,您也可以绑定到a.b.c。 Angular即时创建对象和属性。

<input type="text" ng-model="a.b.c" />

但是你试图绑定到一个尚不存在的数组元素:

<input type="text" ng-model="a.b[0].c" />

Angular将实例化数组,然后在其中推送一个空对象,然后分配它的名称。显然这不起作用。

答案 1 :(得分:1)

我遇到了同样的情况并尝试了一切。

这就是我能够在2深度ng-repeat内获得动态值的方法:

JS:

$scope.newContact = {
    name: [],
    phone: [],
    email: [],
    notes: []
};

$scope.saveNewContact = function (idx) {
    console.log($scope.newContact.name[idx]);
};

HTML:

<input type="text" ng-model="newContact.name[$index]" />
<input type="text" ng-model="newContact.phone[$index]" />
<input type="text" ng-model="newContact.email[$index]" />
<input type="text" ng-model="newContact.notes[$index]" />
<button ng-click="saveNewContact($index)">Save</button>