My data model is something like the following
records
└─ record
└─ id: 0
└─ name: "Foo"
└─ property: true
└─ record
└─ id: 1
└─ name: "Bar"
└─ property: false
└─ record
└─ id: 2
└─ name: "Baz"
└─ property: true
And I want to create a user interface to it using something like the following:
<div class="row">
<input type="hidden" value="0"></input>
<input type="text" value="Foo"></input>
<input type="checkbox" checked></input>
<button>Remove</button>
</div>
...
I am using angular for my project, and the code snippet I have is
<div ng-controller="ThingsController">
<div class="row" ng-repeat="thing in things" ng-controller="ThingController">
<input type="hidden" ng-model="id"></input>
<input type="text" ng-model="name"></input>
<input type="checkbox" ng-model="property"></input>
<button ng-click="remove()">Remove</button>
</div>
</div>
with the following controllers:
angular.module('mymodule', [])
.controller('ThingsController', function($scope) {
$scope.things = [{
id: 0,
name: "Foo"
property: true
}, {
id: 1,
name: "Bar"
property: false
}, {
id: 2,
name: "Baz"
property: true
}];
$scope.remove = function(idx) {
$scope.things.splice(idx, 1);
};
$scope.add = function() {
$scope.things.push({
id: $scope.things.length,
name: 'Placeholder',
property: true
});
};
})
.controller('ThingController', function($scope) {
$scope.remove = function() {
$scope.$parent.remove($scope.$index);
};
});
This code doesn't work - a new set of input fields are created when we push to ng-repeat, but the models are not connected up correctly. When I inspect the situation, I see that there are actually 2 scopes, one for the ng-repeat
and within this another for the ng-controller
.
My question is: what am I doing wrong? Do I need to not use a new controller? Does anyone use this pattern to create variable length forms?