javascript - 使用索引器时 ngModel "Cannot set property of undefined"

标签 javascript angularjs

我有以下标记

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

相关文章:

javascript - 在循环完成nodejs请求之前执行回调

javascript - learnyounode 文件服务器 为什么要把 createReadStream() 放在 createServer() 里面?

javascript - 不使用关闭按钮隐藏模态窗口

angularjs - 在后端的 typescript/angular2 环境和 nodejs 中设置持久 session 时遇到问题

angularjs - Visual Studio 2013 AngularJS 智能感知支持

css - ng-class 条件不起作用

javascript - Bootstrap 计数器开始显示

javascript - 在 AngularJS 中将对象放入数组中

javascript - 连接到 ng-model 的 Angular 数组值

javascript - 如何在 Angular JS 中打开网站时加载特定页面