I have a simple app that lists contact reports, in it i made a list view that fetches data from Mongolab.
On that i also made an input form that makes a new contact report in the list when submitted
the function i use in the controller is modelled from angular's example on their site :
app.factory('Contact',function($mongolabResource){
return $mongolabResource('contacts');
});
function ContactCreateCtrl($scope,$location,Contact) {
Contact.save(contact,function(){
$location.path('/');
});
};
the $location.path() is the callback that reloads the page.
how do i rewrite this so that when the data has been submitted ( .save() is successful ) the view reloads without the page reloading?
i tried deleting and then redefining the array but doesnt seem to work :
Contact.save(contact,function(){
delete $scope.contacts;
$scope.contacts = Contact.query();
});
i would like to implement this on the delete function as well. Can somebody point me to where i can learn this?
Much thanks for any help
Okay, I updated your fiddle to fetch the value from the database: http://jsfiddle.net/joshdmiller/Y223F/2/.
app.controller( 'MainCtrl', function ( $scope,Contact ) {
$scope.updateContacts = function () {
Contact.query( function( data ) {
$scope.contacts = data;
});
};
$scope.save = function( newContact ) {
Contact.save( newContact, function() {
$scope.updateContacts();
});
};
// The initial data load
$scope.updateContacts();
});
Two things to note:
(1) I moved your Mongo query into a function so that it can be called again when the new record is created;
(2) the $mongolabResource expects a callback to be executed on success; your app flickered because you didn't provide one. In other words, from the time you called the query to the time fetch was complete, your list was empty. Instead, we want it to change only when we get the new data. I changed that too.
In terms of adding the item manually or fetching from the database, best practice is based on the use case and there are trade-offs. But for small data such as this, just fetch from the DB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With