I have an API which takes objects e.g.
{
'title': 'Some',
'desc': 'thing',
'environments': '[
{'id': 1},
{'id': 2}
]
}
To add new entries i have a form for setting the title and the description for the object i'm going to pass to my API:
<form class="form horizontal"role="form" ng-submit="vm.submitForm()">
<label for="Title">Title</label>
<input class="form-control"
id="Title"
type="text"
ng-model="vm.myObj.title"
placeholder="Title"/>
<label for="Desc">Description</label>
<input class="form-control"
id="Desc"
type="text"
ng-model="vm.myObj.desc"
placeholder="Description"/>
<div class="checkbox" ng-repeat="env in vm.availableEnvs">
<label>
<input type="checkbox" />
{{env.label}}
</label>
</div>
<hr />
<button>Submit</button>
</form>
In the form you probably saw that i had a ng-repeatthat repeats over an array of environment objects:
this.environments = [
{ id: 1, label: "US" },
{ id: 2, label: "EU" },
{ id: 3, label: "ASIA" },
{ id: 4, label: "AFRICA" }
];
Since the API need to get an array of: {id: x } objects, i was wondering if anyone has a good way for adding (and removing) object details to myObj.environmentsarray when you check or un-check a checkbox?
My .js code: Link to JSFiddle Here
(function(){
angular
.module('myApp', [])
.controller('MyCtrl', MyCtrl)
.service('EnvService', EnvService);
MyCtrl.$inject = ['EnvService'];
function MyCtrl(EnvService) {
var vm = this;
vm.availableEnvs = EnvService.getAvailableEnvironments();
vm.myObj = {
title: '',
desc: '',
environments: []
};
vm.submitForm = submitForm;
function submitForm() {
//Call a service that handles $http and makes a POST with myObj
}
}
function EnvService() {
this.environments = [
{ id: 1, label: "US" },
{ id: 2, label: "EU" },
{ id: 3, label: "ASIA" },
{ id: 4, label: "AFRICA" }
];
this.getAvailableEnvironments = function() {
return this.environments;
}
}
})();