<...">

NgModel "Unable to set undefined property" when using indexer

I have the following markup

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

looks like that:

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

When I try to set a column value that does not exist yet, I get

"Cannot set the 'val' property from undefined."

An example here is http://jsfiddle.net/z9NkG/2/

The documentation notes:

ngModel will attempt to bind the property specified by evaluating the expression in the current scope. If the property does not already exist in this area, it will be created implicitly and added to the area.

But this fails when using an indexer instead of a property name.

Is there a way to define a dynamic ngModel expression or is it wrong to use angular?

+4
4

:

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

Fiddle: http://jsfiddle.net/z9NkG/8/

+3

, , 2- . , ,

cols rowL

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

, undefined undefined . Angular , row[col] row[col].val:

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

: http://jsfiddle.net/z9NkG/9/

0

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

        });
    })

yo http://jsfiddle.net/z9NkG/10/

0

All Articles