I am using node-webkit in conjunction with AngularJS and MySQL. I am fetching customers from MySQL DB using Node.js's mysql driver. Using $q service of angular I want to bind this to the UI which I am unable to.
HTML:
<div class="span4" ng-repeat="customer in customers">
<p><strong>Name: </strong> {{customer.name}}</p>
<p><strong>Address: </strong> {{customer.address}}</p>
<p><strong>Notes: </strong> {{customer.notes}}</p>
</div>
Controller:
myApp.controller('CustomerController',
function CustomerController($scope, CustomerService) {
$scope.customers = CustomerService.getAllCustomers();
});
Service:
var mysql = require('mysql');
myApp.factory('CustomerService', function($q) {
return {
getAllCustomers: function() {
var deferred = $q.defer();
var connection = get_connection();
var query = connection.query('SELECT * from customers;',
function(err, customers) {
if (err) { console.log(err); deferred.reject(err); };
console.log(customers);
deferred.resolve(customers);
connection.end();
}
);
console.log(query.sql);
return deferred.promise;
}
}
});
The SQL works fine and also returns the array. But UI doesn't show the data on fulfilling the promise. What am I missing?
In your controller:
CustomerService.getAllCustomers().then(function(customers){
if(customers){
$scope.customers = customers;
}
});
The promise is not what you think it is :).
Edit: Also as I said in the comments, I wouldn't perform mysql queries directly from angularJS. Use nodeJS or other server side frameworks to do it.
Edit2: The solution this query problem in particular was to use $scope.$apply in the callback method. This has to do with the digest cycle: How do I use $scope.$watch and $scope.$apply in AngularJS?