codedoll codedoll - 4 months ago 20
AngularJS Question

ng-model as initial input on form

I have an edit form that pushes data to a mongo db using express and angular. I am using ng-model for my data. The PUT works correctly to update the database. But I can't seem to make that found data as initial values on the input fields in my GET. I think I am binding thinks incorrectly. If that is the case, what am I doing wrong?
Thanks in advance.

My controller

app.controller('EditController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {

var self = this;
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
self.id = $routeParams.id;
self.name = response.data.name;
self.age = response.data.age;
self.gender = response.data.gender;
self.img = response.data.img;
});

this.editForm = function() {
console.log('editForm');
console.log('Formdata: ', this.formdata);

$http({
method: 'PUT',
url: '/users/' + $routeParams.id,
data: this.formdata,
}).then(function(result) {
self.formdata = {}
});
} // end editForm

}]);
// end EditController

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$locationProvider.html5Mode({enabled:true});

$routeProvider.when('/', {
templateUrl: 'partials/match_partial.html'
}).when('/edit/:id', {
templateUrl: 'partials/edit_partial.html',
controller: 'EditController',
controllerAs: 'editctrl'
})

}]);


My HTML

<div>
<a ng-href="/">
<br>
<h3 class="back">Back to Match</h3>
</a>
<h1 class="editHeader">
Edit {{editctrl.name}}
</h1>
<form ng-submit="editctrl.editForm()">
<input type="text" ng-model="editctrl.formdata.id" placeholder="{{editctrl.id}}">
<input type="text" ng-model="editctrl.formdata.name" placeholder="{{editctrl.name}}">
<input type="text" ng-model="editctrl.formdata.age" placeholder="{{editctrl.age}}">
<input type="text" ng-model="editctrl.formdata.gender" placeholder="{{editctrl.gender}}">
<input type="text" ng-model="editctrl.formdata.img" placeholder="{{editctrl.img}}">
<input type="submit">
</form>
</div>

Answer

You can simply set the whole object to receive the response.data, this way:

$http({
  method: 'GET',
  url: '/users/' + $routeParams.id,
  data: $routeParams.id
}).then(function(response) {
  // console.log(response.data);      
  // Here 
  self.formdata = response.data;
});

And it will automatically fills all inputs with the object properties.

Comments