Currently, I have a service that retrieves a list of students asynchronously using a callback function:
studentModule.factory('StudentService', function (DB_URL) {
return {
getAllStudents: function (callback) {
var Datastore = require('nedb'),
path = require('path');
db = {};
db.students = new Datastore({
filename: DB_URL + '/students.db',
autoload: true
});
db.students.find({}, function (err, stds) {
callback(stds);
});
}; //end return
Initially, I was making use of this service in the controller in the following manner:
StudentService.getAllStudents(function(sts) {
$scope.students = sts;
$scope.$apply();//notify angular about the change
});
While this method has served me well, I now aim to incorporate some best practices. I intend to resolve the result in the route before reaching the controller. Here's how I modified it:
.state('payment', {
url: '/payment',
templateUrl: 'frontend/components/payment/views/payment.html',
controller: 'PaymentController',
resolve: {
students: function (StudentService, $q) {
var defer = $q.defer();
defer.promise.then(function () {
StudentService.getAllStudents(function (sts) {
alert(JSON.stringify(sts));
return sts;
});
})
defer.resolve();
}
}
})
Although the alert successfully displays data from the route, it appears as undefined in the controller:
paymentModule.controller('PaymentController', function($scope, students) {
alert(JSON.stringify(students));
Any assistance on this matter would be greatly appreciated!