Reputation: 3329
I'm trying to make a quick little data-grid directive with editing for a project. Here's the code sans directive.
HTML
<div> </div>
<div ng-app="app">
<div ng-controller="ctrl">
<table class=pure-table pure-table-striped>
<tr ng-repeat="row in data">
<td ng-repeat="col in row"><input ng-model="col"></td>
</tr>
</table>
<p>{{data}}</p>
</div>
</div>
JS
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
$scope.data = [
[100, 200, 300],
[400, 500, 600]
];
});
CSS
td input { border: none; text-align: right; width: 5em; }
And the codepen: http://codepen.io/mikeward/pen/gwcjt
This "almost" works except the data model never gets updated even though I'm using two-way binding (it's behaving as one-way at the moment). Is this an Angular bug or am I just not understanding something?
Upvotes: 3
Views: 4564
Reputation: 2145
Write ng-model="row[$index]"
instead of ng-model="col"
.
I'm not sure about the reason, but this appears similar to likewise problems with Forms and Inputs. I believe that the input creates a child scope. col
is just a scalar variable, so when the scope is copied, the col
in the copy ends up being a totally separate variable. Changes to the copy of col
will thus not change the original. row
on the other hand is a non-scalar variable and this gets "copied" by "reference", therefore any changes to row
in the input will also change the original row
.
The AngularJS people stress that having a scalar variable in ng-model
is doing it wrong. They advise that there shall be a dot in the ng-model
. row[$index]
does not contain a dot but is basically just row.$index
with $index
interpolated first.
Upvotes: 4