javascript - angular js controller with async scope, websql -
javascript - angular js controller with async scope, websql -
i'm trying build first application angularjs. i'm building tizen os, , utilize jquery mobile, doesn't matter in case.
as persistent storage have chosen websql. found nice wrapper angular module - angular-websql. figured out more or less how simple angular controllers work, websql stuff asynchronous, makes things complicated me.
i came out approach, i'm not sure if "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; < results.rows.length; i++) { handler(results.rows.item(i)); } callback(); }); } homecoming user; }) .controller('barctrl', function ($scope, user) { $scope.add = function () { user.insert({ name: $scope.name, lastname: $scope.lastname //and on }, updateusers) } function updateusers() { $scope.users = [] foo.selectall(function(elem) {$scope.users.push(elem)}, $scope.$apply}); } });
as comes code, have manually update expense
binding 1 time record added database (as action asynchronous). have phone call $scope.$apply
then. there way avoid it? there way utilize angular promises @ least, maybe makes things better? sense code can improved, not sure in direction, though. help appreciated.
i (imho) should wrap much of websql service factory. build out returned object list in service , agree using promise thing do. when interact outside of angular binding, need scope.apply should in service. though there callback stuff in angular, urge refrain introducing build in angular code. much more readable.
for me, seek purist , recommend hiding 3rd party libraries controller code , maintain in services , directives. doing create code in ng-way , can create unit testing much easier. have ability swap out new library without breaking defined contract.
make sense?
javascript angularjs cordova asynchronous web-sql
Comments
Post a Comment