ngModel 使用索引器时“无法设置未定义的属性”

ngModel "Cannot set property of undefined" when using indexer

本文关键字:设置 未定义 属性 索引 ngModel      更新时间:2023-09-26

>我有以下标记

<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>

控制器看起来像这样

function test($scope) {
    $scope.cols = ["col1", "col2", "col3"];
    $scope.rows = [{
        col1: { val: "x"}
    }, {
        col2: { val: "y" }
    }]
}

当我尝试设置尚不存在的列值时,我得到

"无法设置未定义的属性'val'"。

示例在这里 http://jsfiddle.net/z9NkG/2/

在文档中有注释:

ngModel 将尝试通过评估 当前作用域上的表达式。如果该属性尚不存在 在此作用域上,将隐式创建它并将其添加到作用域中。

但是,当使用索引器而不是属性名称时,它会失败。

有没有办法动态定义ngModel表达式,还是我滥用了角度?

那呢:

<input type="text" ng-model="row[col].val" ng-init="row[col] = row[col] || {}" />

小提琴:http://jsfiddle.net/z9NkG/8/

我不确定您的模型,但我认为您使用的是二维数组。我过于简单化了,不知道,

使列集合成为子集合或行L

function test($scope) {
    $scope.colnames = ["col1", "col2", "col3"];
    $scope.rows = [{
        cols: { col1: "x"},  { col2: "y"}
    }, {
        cols: { col1: "z"},  { col2: "a"}
    }]
}

然后使用嵌套的 ng 重复

  <table>
    <tbody>
        <tr ng-repeat="row in rows">
            <td ng-repeat="col in row.cols">
                <input type="text" ng-model="col.val" />
            </td>
        </tr>
    </tbody>
  </table>

主要问题是您将未定义对象的未定义属性设置为输入的模型。Angular 确实会自动为您的模型绑定创建相应的变量,但要做到这一点,您必须将输入直接绑定到 row[col] 属性而不是row[col].val

<input type="text" ng-model="row[col]" /> 

这是现场演示: http://jsfiddle.net/z9NkG/9/

试试这个

在控制器中进行更改添加以下代码

 $scope.cols.forEach(function(x, y) {
        angular.forEach($scope.rows, function(i, j) {
            if ((i[x])== null)
                i[x] = {};
        });
    })

哟可以参考小提琴 http://jsfiddle.net/z9NkG/10/