javascript - Autosave with angular $resource -


i trying implement editor model lot of fields has autosave feature.

the model json, loaded $resource , used directly in scope.

 mymodelresource = $resource(config.api4resource + 'models/:id', {id:'@_id'});  $scope.mymodel = mymodelresource.get({id: xxxx}); 

problem #1: actual autosave implementation. each text field doing:

html:

<input type="text" ng-model="mymodel.somefield" ng-blur="save()" ng-change="dirty()"> 

controller:

$scope.dirty = function() {     $scope.dirtyflag = true;     console.log('marking dirty!'); };  $scope.save = function(force) {      if (!$scope.dirtyflag && !force) {         return;     }     $scope.dirtyflag = false;     console.log('saving!');     $scope.mymodel.$save(); } 

the idea is, saving on each ng-change expensive, don't want hit server every letter user types. ng-change() marks "dirty" flag in controller, , when move away field ng-blur, check flag , save if state dirty. still doesn't cover cases, case when user modified text field did not move field. there option schedule timer save() within dirty(), save anyway, doesn't elegant solution me (the timer code taken https://stackoverflow.com/a/21137079/1076865):

$scope.dirty = function() {     $scope.dirtyflag = true;     console.log('marking dirty!');      if (savepromise) {         $timeout.cancel(savepromise);     }      savepromise = $timeout(function() {         savepromise = null;         $scope.save();     }, 500); }; 

what common ways of solving problem?

problem #2: once save code hit, calling mymodel.$save() function. sends post request server, server saves in db , replies same model response.

and here problem, seems cause reload of mymodel, causes reflow of portions of webpage , focus being lost. if user typed , pressed tab move next field, moment later (once reply comes back) focus disappears new field. pretty annoying. how can solve problem? need keep 2 copies of model myself (one used $resource , 1 on $scope), , keep track manually of changes between two? doesn't sound angular way, there must better solution.

thanks!

problem #1

i use lo-dash debounce. quick google search shows how auto save angular , debounce prevents having add ng-blur , ng-change each input. , should more efficent users edit multiple inputs quickly.

problem #2

sounds $scope.$apply() or $scope.$digest() being called after resource.$save() not sure why.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -