创建“下一条记录/上一条记录”按钮
Create a "next record/previous record" button in Angular
我有一个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
相关文章:
- 在检索到最后一条记录后从 PostgreSQL 中提取记录
- 子网格:限制用户仅选择一条记录
- CSS悬停在JQuery循环的最后一条记录中不起作用
- 数据中的一条记录使用浮动图时未创建饼图
- “自动完成”文本框未前进到下一条记录
- 如何使用 JavaScript 函数在 JSP 中使用按钮移动到数据库的最后一条记录
- 剑道网格在删除后仍显示最后一条记录
- 如何使用angularJs/Javascript/Jquery获取表的最后一条记录并更新列值并插入到具有新记录的同一列
- 角度拼接函数删除另一条记录而不是实际选择的记录
- Jquery在“下一条记录”上加载当前选项卡
- 数据存储在ember中只返回一条记录
- Ember data find()方法返回数组,但我需要一条记录
- 在服务器不知道查询的是哪条记录的情况下,查询服务器是否存在一条记录
- php . .使用文本文件在分号表中插入(追加)一条记录
- 使用angularjs更新一条记录
- 使用sequelize获取下一条记录
- MongoDB确定一条记录是否会通过findOne
- 创建“下一条记录/上一条记录”按钮
- 在Ember.js中创建并读取一条记录
- 带有最后一条记录的While循环