上次写了篇Spring CRUD的简单例子,没想到很多人访问,由于本人在学习AngularJs中文社区的翻译文章很头疼,所以自己写了个简单的Spring AngularJs的练练手,先说明下:
1)例子没有使用数据库,数据都传送到后台了,想使用Hibernate或者Mybatis保存到数据库请自行添加代码,相信这一步会很容易。
2)页面文件在index.jsp。
3)本人接触AngularJs不到一周,代码中难免有错误,如有错误,请指正,谢谢。
4)时间控件没有使用My97datepicker,因为本人没整合成功,有整合成功的,可以分享下。
5)感兴趣的朋友可以看下下面的博文,http://www.zouyesheng.com/angular.html ,http://www.cnblogs.com/liulangmao/tag/angular/, http://my.oschina.net/buwei/blog/191640
例子运行结果如下:
修改
<tr ng-repeat="user in users" ng-class="$index % 2 == 0 ? 'even' : 'odd';">
后支持隔行变色,如下:
下面说下关键的代码。
首先是新增或者修改,代码如下:
$scope.commitUser= function(varUser) {
if($scope.isAdd==true){
$scope.url ='/Spring_Angular_Demo/user/list/addUser';
varUser.region=$scope.regionId;
varUser.county=$scope.countyId;
$http.post($scope.url, varUser).success(function(data){
//重新加载数据
$scope.url='/Spring_Angular_Demo/user/list/all';
$http({
method: 'GET',
url: $scope.url
}).success(function(data){
$scope.ifShow = true;
$scope.sysInfo = '添加成功';
$scope.users=data;
}).error(function(){
$scope.ifShow = true;
$scope.sysInfo = '系统错误,请刷新页面';
});
}).error(function(){
$scope.ifShow = true;
$scope.sysInfo = '系统错误,请刷新页面';
});
}else{
$scope.url ='/Spring_Angular_Demo/user/list/updateUser';
varUser.region=$scope.regionId;
varUser.county=$scope.countyId;
$http.post($scope.url, varUser).success(function(){
$scope.url='/Spring_Angular_Demo/user/list/all';
$http({
method: 'GET',
url: $scope.url
}).success(function(data){
$scope.ifShow = true;
$scope.sysInfo = '修改成功';
$scope.users=data;
}).error(function(){
$scope.ifShow = true;
$scope.sysInfo = '系统错误,请刷新页面';
});
});
}
}
结果为:
删除操作,代码如下:
$scope.removerUser = function(varUser) {
$scope.ifShow = false;
$scope.url='/Spring_Angular_Demo/user/list/deleteUser';
$http({
method: 'GET',
url: $scope.url,
params: {userId:varUser.id}
}).success(function(data){
$scope.ifShow = true;
$scope.sysInfo = '删除成功';
var index = $scope.users.indexOf(varUser);
if (index != -1) {
$scope.users.splice(index, 1);
}
}).error(function(){
$scope.ifShow = true;
$scope.sysInfo = '系统错误,请刷新页面';
});
$scope.user={};
$scope.isAdd=true;
$scope.ifShow = false;
}
结果为:
select框onChange事件处理,代码如下:
//显示的文字,提交时候为数字id
$scope.onSelectChange=function() {
var county=$scope.user.county;
$scope.ifShow = false;
var keepGoing = true;
angular.forEach($scope.counties, function(k,v){
if(keepGoing) {
if(v == county){
$scope.user.county=k;
$scope.countyId=v;
keepGoing = false;
}
}
});
}
其他的代码请看附件。
全文完。