我有以下标记
<div ng-app>
<table ng-controller="test">
<tbody>
<tr ng-repeat="row in rows">
<td ng-repeat="col in cols">
<input type="text" ng-model="row[col].val" />
</td>
</tr>
</tbody>
</table>
</div>
Controller 看起来像这样
function test($scope) {
$scope.cols = ["col1", "col2", "col3"];
$scope.rows = [{
col1: { val: "x"}
}, {
col2: { val: "y" }
}]
}
当我尝试设置尚不存在的列值时,我得到
"Cannot set property 'val' of undefined".
示例在这里 http://jsfiddle.net/z9NkG/2/
文档中有注释:
ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.
但是当使用索引器而不是属性名称时它会失败。
有没有办法动态定义 ngModel 表达式,还是我滥用了 angular?
最佳答案
然后呢:
<input type="text" ng-model="row[col].val" ng-init="row[col] = row[col] || {}" />
fiddle :http://jsfiddle.net/z9NkG/8/
关于javascript - 使用索引器时 ngModel "Cannot set property of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19152020/