【问题标题】:Angular JS Handle controller EventsAngular JS 处理控制器事件
【发布时间】:2014-08-22 12:19:25
【问题描述】:

我有一个应用程序有很多东西要以级联方式保存,成像一个普通的主-细节视图。

在这个视图中,我有一个“全部保存”按钮,它在迭代中保存每一行,触发 jQuery 自定义事件,以序列化保存操作并防止生成不受控制的请求队列。

每次保存一行时,程序都会递减计数器并启动新行的保存。

当没有行可保存时,一切都结束了(计数器 = 0)。

这是一个代码 sn-p 这样做:

var save_counter = -1;

// Creates a counter and save content header when finished to save rows.
var updCounter = function(evt){

    // Update Counter
    save_counter--;
        
    // Register updates When there are not rows to skip
    if ((save_counter===0) 
        || (save_counter===0 && edit_status == "modified") ){

        console.log('Persist Master');
        $(document).trigger('save_ok');

    }
};    

saveRows = $(form_sel);

// Reset Save Counter
save_counter = saveRows.length;

// Iterate through lines
saveRows.each(function(idx){
    var form = $(this);

    // Execute Uptade Counter once
    form.one(update_counter, updCounter);

    // Per each performed save, decrese save counter
    form.trigger('submit');
});

现在我正在使用 angular 迁移一些关键的应用程序模块,但我不知道这样做。

有执行批处理请求调用的最佳实践吗?

使用$scope 变量和$watch 是不是一个好主意,使用类似的东西?

var RowController = angular.controller('RowController', function($scope, $http){

    $scope.rows = [
          {id : 1, title : 'lorem ipsum'}
        , {id : 2, title : 'dolor sit amet'}
        , {id : 3, title : 'consectetuer adipiscing elit'}
    ];

    // Counter Index
    $scope.save_counter = -1;

    // "Trigger" the row saving, changing the counter value
    $scope.saveAll = function () {
        $scope.save_counter = 0;
    };
    
    // Watch the counter and perform the saving
    $scope.$watch('save_counter', function(

        // Save the current index row
        if ($scope.save_counter >= 0 
                && $scope.save_counter < $scope.rows.length) {

            $http({
                url : '/row/' + $scope.rows[$scope.save_counter].id, 
                data: $scope.rows[$scope.save_counter]
            }).success(function(data){
                
                // Update the counter ...
                $scope.save_counter ++;

            }).error(function(err){

                // ... even on error
                $scope.save_counter ++;
            });

        };

    ));
});

【问题讨论】:

  • RowController 之后添加了',假设有错别字。

标签: javascript jquery angularjs jquery-events


【解决方案1】:

最好的方法是使用带有承诺的service ($q)。

这是一个例子:

app.factory('RowService', function($http, $q) {
  return {
    saveRow: function(row) {
      return $http({
        url: '/row/' + row.id,
        data: row
      });
    },

    saveAll: function(rows) {
      var deferred = $q.defer();
      var firstRow = rows.shift();
      var self = this;

      // prepare all the saveRow() calls
      var calls = [];
      angular.forEach(rows, function(row) {
        calls.push(function() {
          return self.saveRow(row);
        });
      });

      // setup the saveRow() calls sequence
      var result = this.saveRow(firstRow);
      angular.forEach(calls, function(call) {
        result = result.then(call);
      });

      // when everything has finished
      result.then(function() {
        deferred.resolve();
      }, function() {
        deferred.reject();
      })

      return deferred.promise;
    }
  }
});

在你的控制器上:

app.controller('RowController', function($scope, RowService) {
  ...

  $scope.saveAll = function() {
    // $scope.rows.slice(0) is to make a copy of the array
    RowService.saveAll($scope.rows.slice(0)).then(
      function() {
        // success
      },
      function() {
        // error
      })
  };
});

查看此plunker 以获取示例。

【讨论】:

  • 好的,非常感谢!只是另一个,这个成功/错误调用是全局的吗? RowService.saveAll($scope.rows.slice(0)).then( function() { // success }, function() { // error }) 特定行的 ajax 错误/成功在 saveRow 函数中处理,对吗?
  • 您可以在全球范围内使用它们。如果$http 请求之一失败,错误将传播到RowController 中定义的回调。
  • 我不明白使用超时来推迟请求调用的方法。我在plunker上稍微改了一下:plnkr.co/edit/OPsiQ187FeOjcoKpBJwT,希望有用。
  • 超时时间仅供演示,请勿使用。 $http 服务已经返回了一个承诺,所以不需要手动推迟它:saveRow: function(row) { return $http.post(/* parameters */); }
猜你喜欢
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多