现在越来越多的应用程序都在向前后端分离的模式方向进行发展,前端注重页面样式和页面功能,后端注重代码功能,从而实现分工合作,达到效率和功能齐头并进的效果。
有时候因为前端的部分数据是从后端响应回来的,但是呢,后端功能还没实现,会导致前端部分功能停滞不前,从而也就影响了工作的效率。
有人选择等待后端的功能完成,有人选择自己造数据,有人...
为了解决这个问题,就出现了Mock.js,Chance.js等外部js,其能随机生成数据供页面使用。本文主要已Mock.js作为案例来模拟生成一个表格数据。更多配置请参考Mock.js官网,Mock.js的随机数据参考了Chance.js官网。
Demo.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div ng-app="app">
<div ng-controller="ctrl">
<table border="1" cellspacing="0">
<thead>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>生日</th>
<th>出生地</th>
</thead>
<tbody>
<tr ng-repeat="user in users">
<!-- <td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.birthday}}</td>
<td>{{user.city}}</td> -->
<td>
<span ng-bind="user.id"></span>
</td>
<td>
<span ng-bind="user.name"></span>
</td>
<td>
<span ng-bind="user.age"></span>
</td>
<td>
<span ng-bind="user.birthday"></span>
</td>
<td>
<span ng-bind="user.city"></span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="http://mockjs.com/dist/mock.js"></script>
<script src="https://cdn.bootcss.com/angular.js/1.6.9/angular.min.js"></script>
<script type="text/javascript">
// Mock响应模板
Mock.mock('http://test.com', {
"users|5-10": [{ // 随机生成5到10个数组元素
'name': '@cname', // 中文名称
'id|+1': 1, // 属性值自动加 1,初始值为1
'age|18-28': 0, // 18至28以内随机整数, 0只是用来确定类型
'birthday': '@date("yyyy-MM-dd")', // 日期
'city': '@city(true)', // 中国城市
}]
});
angular.module('app', [])
.service('userService', ['$http', function ($http) {
return {
doRequest:function(){
return $http({
url:'http://test.com',
method:'post'
});
}
};
}])
.controller('ctrl', ['$scope', 'userService', function ($scope, userService) {
userService.doRequest().then(function success(response){
console.log(response);
$scope.users = response.data.users;
}, function error(){
console.error('error...');
})
}]);
</script>
</body>
</html>
Demo结果1:
刷新一下浏览器后,得到
Demo结果2:
两次结果都是随机的,从而达到快速开发的功能。
当然,这种开发也是有前提的,那前提就是熟悉Mock.js的配置,其实这也是引入外面js的一个通病----不熟悉,为了达到一个效果,不得不先学习这个js的配置等等,所以也会影响开发效率。
个人建议,先实现功能,在有业余的时候的时候再使用外部js来实现更丰富的功能。仁者见仁,智者见智。
====================打个广告,欢迎关注====================
QQ: | 412425870 |
csdn博客: | http://blog.csdn.net/caychen |
码云: | https://gitee.com/caychen/ |
github: | https://github.com/caychen |
点击群号或者扫描二维码即可加入QQ群: | |