多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
取教师列表的职能应该放在teacher M层中,我们在 services/teacher.js中增加all()方法。 ``` 'use strict'; /** * @ngdoc service * @name webAppApp.teacher * @description * # teacher * Service in the webAppApp. */ angular.module('webAppApp') .service('teacher', function(server) { /** * 获取当前页的教师 * @param {string} name 查询教师的名字 * @param {int} page 第几页 * @param {int} pageSize 每页多少条 * @param {Function} callback 回调函数 * @return {[type]} * @author 梦云智 http://www.mengyunzhi.com * @DateTime 2017-01-21T19:05:55+0800 */ var paginate = function(name, page, pageSize, callback) { var teachers = []; // 进行http POST请求. // 由于是post请求方式,所以即便是我们在项目中存在paginate.json文件 // 但如果我们查看控制台,仍然会发现有错误产生,同时,没有正确的接收到数据 server.http({ method: 'POST', url: '/teacher/indexJson', data: { name: name, page: page, pageSize: pageSize } }, function(response) { teachers = response.teachers; callback(teachers); }); }; // 获取所有的教师列表 var all = function(callback) { var teachers = []; server.http({ method: 'GET', url: '/Teacher_all.json', }, function(response) { teachers = response.teachers; callback(teachers); }); }; // Public API here return { // 获取全部教师信息 paginate: function(name, page, pageSize, callback) { return paginate(name, page, pageSize, callback); }, all: all, }; }); ``` ## 单元测试 同样,在有后台的数据支持的情况下,我们只需要给出测试值即可 ``` 'use strict'; describe('Service: teacher', function() { // load the service's module beforeEach(module('webAppApp')); // instantiate service var teacher, $httpBackend, config; // 引用$httpBackend beforeEach(inject(function(_teacher_, _$httpBackend_, _config_) { teacher = _teacher_; $httpBackend = _$httpBackend_; config = _config_; var url = config.apiRootPath + '/Teacher_all.json'; var data = {code: 200, teachers: []}; $httpBackend.when('GET', url).respond(data); })); it('应该取出来所有的教师数据', function() { teacher.all(function(teachers) { console.log(teachers); }); // 模拟数据请求 $httpBackend.flush(); }); }); ``` # C与M对接 ``` 'use strict'; /** * @ngdoc function * @name webAppApp.controller:KlassAddCtrl * @description * # KlassAddCtrl * Controller of the webAppApp */ angular.module('webAppApp') .controller('KlassAddCtrl', function($scope, config, teacher) { $scope.name = ''; // 名称 // 教师列表 $scope.teachers = []; // 选中的教师 $scope.teacher = 0; $scope.isDebug = config.isDebug; var submit = function() { console.log('submit'); }; // 获取教师列表 var getTeachers = function() { teacher.all(function(response){ $scope.teachers = response; // 获取到的所有教师 $scope.teacher = $scope.teachers[0].id; // 初始化选中的教师 }); }; // 初始化 var int = function () { getTeachers(); }; int(); $scope.submit = submit; }); ``` > git checkout -f step12.2.4