Angular JS处理控制器事件

Angular JS Handle controller Events

本文关键字:事件 控制器 处理 JS Angular      更新时间:2023-09-26

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

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

每保存一行,程序就递减计数器并开始保存新行。

当没有行可以保存(counter = 0)时,一切都结束。

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 ++;
            });
        };
    ));
});

最好的方法是使用带有承诺($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
      })
  };
});

以这个柱塞为例。