摘要完成后,angularjs 保存更改

标签 angularjs angularjs-timeout

我认为这对于任何有 Angular 的应用程序来说可能都是非常常见的用例。我只是在观察范围内的一些对象,这些对象作为几个摘要周期的一部分而发生变化。消化它们(通过数据绑定(bind)更改它们的值)完成后,我想将它们保存到数据库中。

A.现在,使用当前的解决方案,我发现以下问题:

  1. 在 $timeout() 中运行保存 - 如何确保仅调用保存 一次

  2. 在 $scope.$evalAsync 中运行自定义函数 - 如何找出已更改的内容

当然,这两个问题都有解决方案,但我所知道的解决方案对我来说似乎都不那么优雅。

问题是:解决问题的最优雅的解决方案是什么?

B.特别是,最佳实践是什么

  1. 确保在摘要周期中仅调用 save 一次

  2. 在上次摘要后发现该对象

最佳答案

这是我发现最适合我的解决方案 - 作为 AMD 模块。灵感来自下划线。

   /**
     * Service function that helps to avoid multiple calls 
     * of a function (typically save()) during angular digest process.
     * $apply will be called after original function returns;
     */
        define(['app'], function (app) {
            app.factory('debounce', ['$timeout', function ($timeout) {
                return function(fn){ // debounce fn
                    var nthCall = 0;
                    return function(){ // intercepting fn
                        var that = this;
                        var argz = arguments;
                        nthCall++;
                        var later = (function(version){
                            return function(){
                                if (version === nthCall){
                                    return fn.apply(that, argz);
                                }
                            };
                        })(nthCall);
                        return $timeout(later,0, true);
                    };
                };
            }]);
        });


    /*************************/

    //Use it like this: 

    $scope.$watch('order', function(newOrder){
      $scope.orderRules.apply(newOrder); // changing properties on order
    }, true);

    $scope.$watch('order.valid', function(newOrder){
      $scope.save(newOrder); //will be called multiple times while digested by angular
    });

    $scope.save = debounce(function(order){
      // POST your order here ...$http....
      // debounce() will make sure save() will be called only once
    });

关于摘要完成后,angularjs 保存更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16278216/

相关文章:

javascript - 无法更新数据库中的对象

javascript - <abbr> html 标签问号

javascript - 如何将 Controller 变量作为 AngularJS $resource 请求的参数传递?

angularjs - Angular 向导 ng-view 和 angularui modal

angularjs - AngularJS 中的 $evalAsync 和 $timeout 有什么区别?

AngularJS:为什么以及何时需要调用 $timeout?

javascript - Angular.js 中是否有任何事件 "on $scope digest finished"或 "on view refreshed"?

angularjs - ng-animate 脉冲背景颜色通过添加类,然后删除类