Friday, May 10, 2024
188
rated 0 times [  192] [ 4]  / answers: 1 / hits: 40352  / 12 Years ago, sat, january 5, 2013, 12:00:00

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


More From » model-view-controller

 Answers
9

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.


[#81060] Friday, January 4, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;