Reputation: 4671
I've got a form that allows users to create a service. Currently you can only add one provider to that service.
I'd like to allow users to add up to 10 providers, using the "Add Another Provider" button.
Here's my code at the moment:
add-service.html
<form role="form" name="createServiceForm">
<input type="text" ng-model="title">
<h2>Attach Provider</h2>
<input type="text" ng-model="provider.title">
<textarea rows="3" ng-model="provider.description"></textarea>
<button type="submit">Add Another Provider</button>
<button type="submit" ng-click="createService()">Submit</button>
</form>
main.js
$scope.createService = function() {
var newService = {
title: $scope.title,
providers: {
provider: {
title: $scope.provider.title,
description: $scope.provider.description
}
},
};
var promise = ServiceService.add(newService);
};
I could duplicate parts of the code like so:
<input type="text"ng-model="provider1.title">
<input type="text"ng-model="provider2.title">
<input type="text"ng-model="provider3.title">
...
providers: {
provider1: {
title: $scope.provider1.title,
},
provider2: {
title: $scope.provider2.title,
},
provider3: {
title: $scope.provider3.title,
}
...
}
But that seems like a messy solution...
What's the best way to duplicate the provider portion of the form, when you click "Add Another Provider" without repeating it 10 times in my HTML and in my newService
object?
Upvotes: 0
Views: 517
Reputation: 4538
You can accomplish what you want by using ng-repeat. I've made providers into an array, which you can then iterate over. You could use ng-repeat with an object if the key is important to you.
Also added a function which will push a new provider onto the array, which will then show in the form.
main.js
$scope.providers = [];
$scope.addProvider = function() {
$scope.providers.push({
title: '',
description: ''
});
};
// Start with one provider
$scope.addProvider();
$scope.createService = function() {
var newService = {
title: $scope.title,
providers: $scope.providers,
};
var promise = ServiceService.add(newService);
};
addService.html
<form role="form" name="createServiceForm">
<input type="text" ng-model="title">
<h2>Attach Provider</h2>
<div ng-repeat="provider in providers">
<input type="text" ng-model="provider.title">
<textarea rows="3" ng-model="provider.description"></textarea>
</div>
<button ng-click="addProvider()">Add Another Provider</button>
<button type="submit" ng-click="createService()">Submit</button>
</form>
Upvotes: 2