创建“下一条记录/上一条记录”按钮

Create a "next record/previous record" button in Angular

本文关键字:一条 记录 按钮 下一条记录 创建      更新时间:2023-09-26

我有一个AngularJS应用程序,其中一个控制器管理index模板,显示从API调用接收到的记录,另一个控制器管理相应的show模板。

我想在show模板上创建一个前进/后退按钮,以便您可以简单地跳过记录。如果我到达终点,我希望它从起点重新开始——并且是无限循环。

我不确定在哪里放置"记录总数"的逻辑,以便我的show控制器知道我已经达到了结束。只有我的索引控制器有完整的数据集。似乎服务在让控制器说话方面很有用,但我不确定如何在这种情况下实现它。

API调用当前发生在工厂中:

app.factory('studentsFactory', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
  var factory = {};
  factory.getStudents = function() {
    return $http.get('http://localhost:3000/students', { cache: true });   };
  factory.getStudent = function(studentId) {
    return $http.get('http://localhost:3000/students/' + studentId, { cache: true });   };
  return factory;
}]);

…并移交给IndexCtrl:

app.controller('IndexCtrl', ['$scope', 'studentsFactory', function ($scope, studentsFactory) {
  function init() {
    studentsFactory.getStudents()
      .success(function (students) {
        $scope.students = students;
        $scope.length = students.length
      });
    });
  }
  init();
}]);

…和ShowCtrl:

app.controller('ShowCtrl', ['$scope', 'studentsFactory', '$routeParams', function ($scope, studentsFactory, $routeParams){
  var studentId = $routeParams.studentId;
  // var nextId = studentId++  (if < max, go ahead, if not, reset to 1)
  function init() {
    studentsFactory.getStudent(studentId)
      .success(function (student) {
        $scope.student = student;
      });
  });
  init();
}]);

好像就在我面前。工厂还可以将数据从相同的API调用发送到可以存储max作为变量的服务吗?

许多谢谢。

您可以在服务中放置一些next和previous方法,靠近学生数据本身。比如:

factory.nextStudent = function() {
  var deferred = $q.defer();
  rollIndexForward();
  this.getStudent(currentIndex).then(function(student) {
    deferred.resolve(student);
  });
  return deferred.promise;
};
factory.previousStudent = function() {
  var deferred = $q.defer();
  rollIndexBackward();
  this.getStudent(currentIndex).then(function(student) {
    deferred.resolve(student);
  });
  return deferred.promise;
};

然后您可以将这些绑定到控制器中的next()和previous()方法以设置当前学生。

$scope.next = function() {
  studentsFactory.nextStudent().then(function(student) { 
    $scope.currentStudent = student;
  });
};
$scope.previous = function() {
  studentsFactory.previousStudent().then(function(student) { 
    $scope.currentStudent = student;
  });
}

这将保持学生收集逻辑在一起,并将启用重用。

这里有一个活塞:http://plnkr.co/edit/YPqfIDX8USeg0jv6nlGi?p=preview