Reputation: 1195
I have a weird problem with dynamic binding of model in Angular JS.
<tr ng-repeat="i in [].constructor( 5 ) track by $index">
<td ng-repeat="column in columns">
<input type="text" ng-model="column.defaults[i]" class="form-control">
</td>
</tr>
I define columns using:
$scope.addColumn = function() {
if(!$scope.field_column_name) return;
if(!$scope.columns) {
$scope.columns = []
}
$scope.columns.push( {
name: $scope.field_column_name,
defaults: $scope.field_column_defaults
});
$scope.field_column_name = $scope.field_column_default = undefined;
};
My goal is create inputs for all of it to store data added by user. The problem is, because all inputs looks like if they were the same model (value added in one of them shows also in other inputs). Why?
JSFiddle: http://jsfiddle.net/tz6fsz1o/5/
Upvotes: 1
Views: 58
Reputation: 14159
You are binding each field on ng-model="column.defaults[i]"
, it means that each field present in the columns
array will be binded on the same model property... ex: both column.foo
and column.bar
bind to columnt.default[i]
...
You can fix it binding the text field on the column
variable, for example:
<td ng-repeat="column in columns">
<input type="text" ng-model="column.foo" class="form-control">
</td>
Upvotes: 0
Reputation: 3062
You have mistake in creating rows_array
Try http://jsfiddle.net/tz6fsz1o/6/
$scope.$watch('rows', function(){
$scope.rows_array = [];
for(var i=0;i<$scope.rows;i++){
$scope.rows_array.push(i);
}
}, true);
Upvotes: 0
Reputation: 193261
I think it should be like this:
<tr ng-repeat="i in [].constructor(5)" ng-init="outerIndex = $index">
<td ng-repeat="column in columns">
<input type="text" ng-model="columns[$index].defaults[outerIndex]" class="form-control">
</td>
</tr>
Note how you need to store outer loop $index
into helper variable in order to access it in inner loop.
Demo: http://jsfiddle.net/tz6fsz1o/7/
Upvotes: 1