-
Notifications
You must be signed in to change notification settings - Fork 1
08c Callback
Dave Strus edited this page Aug 20, 2015
·
2 revisions
We've invoked many functions that can accept callback functions, but now we're going to rewrite a couple of our own existing functions to make use of callback functions.
noteApp.service('NotesBackend', function NotesBackend($http) {
var notes = [];
this.getNotes = function() {
return notes;
};
this.fetchNotes = function(callback) {
$http.get(nevernoteBasePath + 'notes?api_key=' + apiKey)
.success(function(notesData) {
notes = notesData;
callback(notes);
});
};
this.postNote = function(noteData, callback) {
var self = this;
$http.post(nevernoteBasePath + 'notes', {
api_key: apiKey,
note: noteData
}).success(function(newNoteData){
self.fetchNotes(callback);
});
};
});
noteApp.controller('NotesController', function NotesController($scope, NotesBackend) {
var self = this;
$scope.notes = [];
this.refreshNotes = function(notes) {
var sidebarScope = angular.element(document.getElementById("sidebar")).scope();
sidebarScope.notes = notes;
};
$scope.commit = function() {
var note = {
title: 'Mega-hip title',
body_html: 'Groovy body'
};
NotesBackend.postNote(note, self.refreshNotes);
};
NotesBackend.fetchNotes(this.refreshNotes);
});
Notice the use of the self
trick, enabling us to call fetchNotes
from inside the success
callback within postNote
. I also the initial fetching of notes to the end of the controller, since refreshNotes
needs to be declared before we can pass it as the callback the fetchNotes
.
This all works swimmingly with our mocked data, but we really need to get the data for new notes from our actual form. All really need to do is bind those form elements to our $scope
with ng-model
, so let's do that now.