I'm building a form that should support entering attributes for multiple instances of the same product. To allow a user to create an arbitrary number of instances I'm using ng-repeat
and building an additional version of the form when an "add version" button is clicked. For static inputs this works as expected as a new form is created and the entered values are not linked between instances. However, I'm also intending to support a dynamic list of individual attributes using ng-repeat
and in my current implementation the addVersion()
function is copying both the number of attributes and the values within.
I've read several questions on this topic and it's clear to me I should be using $index
but I'm afraid I'm new enough to Angular that I can't totally get my head around how to do this.
EDIT: Here's a working example that should highlight the problem
For the purpose of clarity I'm hoping to be able to generate a response that looks like:
Product Name: A Car
Product Description: You can sit in it and also drive it
Version 1
Price: $500
Quantity: 3
Features: 1) Goes fast 2) is red
Version 2
Price: $600
Quantity: 4
Features: 1) Goes really fast 2) is blue 3) has windshield wipers
But instead I'm seeing the values in features cloned... which makes sense because I'm clearly pushing them to the same array I just don't know how to change that :)
Right now a simplified version of the code looks like this:
HTML:
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button ng-click="addVersion()">Add Version</button>
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<div ng-repeat="version in versions">
<input type="number" ng-model="instance.price" placeholder="Price">
<input type="number" ng-model="instance.quantity" placeholder="Quantity">
<button ng-click="addInput()">Add Feature</button>
<fieldset ng-repeat="feature in features">
<input type="text" ng-model="instance.feature.name" placeholder="feature">
</fieldset>
</div>
</form>
JS:
$scope.versions = [{}];
$scope.addVersion = function() {
$scope.versions.push({});
};
$scope.features = [];
$scope.addInput = function() {
$scope.features.push({});
};
I think the solution here is stupidly obvious I'm just a bit lost. Thanks!