I'm trying to build my first application with AngularJs. I'm building it for Tizen OS, and I also use Jquery mobile, but that doesn't really matter in this case.
As a persistent storage I have chosen WebSql. I found a nice wrapper as an angular module - angular-websql. I figured out more or less how simple angular controllers work, but all this WebSql stuff is asynchronous, what makes things really complicated for me.
I came out with an approach, but I'm not sure if it is "angular way".
app = angular.module('foo', ["angular-websql"])
.factory('User', function ($webSql) {
db = $webSql.openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.createTable('users', {
// table schema
});
User = {};
User.insert = function(elem, callback) {
db.insert('expenses', elem, callback);
}
User.selectAll = function(handler, callback){
db.selectAll('expenses', function(results) {
for(var i=0; i < results.rows.length; i++) {
handler(results.rows.item(i));
}
callback();
});
}
return User;
})
.controller('BarCtrl', function ($scope, User) {
$scope.add = function () {
User.insert({
name: $scope.name,
lastname: $scope.lastname
//and so on
}, UpdateUsers)
}
function UpdateUsers() {
$scope.users = []
Foo.selectAll(function(elem) {$scope.users.push(elem)}, $scope.$apply});
}
});
As it comes from the code, I have to manually update the expense
binding once the record is added to the database (as that action is asynchronous). I also have to call $scope.$apply
then. Is there a way to avoid it? Is there a way to use angular promises at least, maybe it makes things better?
I feel that this code can be improved, not sure in what direction, though. Any help will be appreciated.