Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh view without refreshing page in an angularjs app

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

like image 288
George Ananda Eman Avatar asked Jan 14 '23 14:01

George Ananda Eman


1 Answers

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.

like image 70
Josh David Miller Avatar answered Jan 29 '23 21:01

Josh David Miller