My first project involving AngularJS has left me a bit stuck when it comes to using the select list. I need to either set the default value to the first option for a new entry, or if it's an edit, select the appropriate value.
In my form, there are two select lists and I suspect that my ng-options tag might be incorrect.
invite.tpl.html
<select ng-model="selectedUser" ng-options="user.id as user.user_name for user in users"></select>
<select ng-model="selectedEvent" ng-options="event.id as event.name for event in events"></select>
The controller responsible for fetching/posting JSON data.
invite.js
.controller('InviteCtrl', function InviteController( $scope, InviteRes, $state, $stateParams ) {
$scope.inviteId = parseInt($stateParams.inviteId, 10);
$scope.users = InviteRes.Users.query();
$scope.events = InviteRes.Events.query();
//EDIT (HAVE ID) - SET SELECTS TO THE USER/EVENT
if ($scope.inviteId) {
$scope.invite = InviteRes.Invites.get({id: $scope.inviteId});
$scope.selectedUser = $scope.invite.user_id;
$scope.selectedEvent = $scope.invite.event_id;
}
//NEW (NO ID) - SET DEFAULT OPTIONS TO FIRST USER/EVENT
else {
$scope.selectedUser = $scope.users[0];
$scope.selectedEvent = $scope.events[0];
$scope.invite = new InviteRes.Invites();
}
Function for saving the data.
$scope.submit = function() {
$scope.invite.user_id = $scope.selectedUser;
$scope.invite.event_id = $scope.selectedEvent;
//IF ID - UPDATE ELSE NEW
if ($scope.inviteId) {
$scope.invite.$update(function(response) {
$state.transitionTo('invites');
}, function(error) {
$scope.error = error.data;
});
}
else {
$scope.invite.$save(function(response) {
$state.transitionTo('invites');
}, function(error) {
$scope.error = error.data;
});
}
};
Defining resources to fetch data from.
.factory( 'InviteRes', function ( $resource ) {
return {
Invites: $resource("../invites/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
Users: $resource('../users.json'),
Events: $resource('../events.json'),
};
})
I've tried various solutions found in articles, but I'm still facing issues with setting values and saving the form correctly.