/java/

AngularJs simple example, backend in java

2013-03-16 21:51:31

Everything on github: https://github.com/szalek/examples/tree/master/app/f_angularjs_b_java

frontend

app.js

'use strict';
/* App Module */

angular.module('postapp', ['postServices']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/posts',         {templateUrl: 'tpl/post-list.html',   controller: PostListCtrl}).
      when('/post/:phoneId', {templateUrl: 'tpl/post-detail.html', controller: PostDetailCtrl}).
      otherwise({redirectTo: '/posts'});
}]);

services.js

'use strict';
/* Services */

angular.module('postServices', ['ngResource']).
factory('Posts', function($resource){
    return $resource('http://localhost\\:8080/angularjs/api/post/:phoneId', {}, 
    {
        all: {method:'GET',params:{phoneId:''},isArray:true}
    });
});

controller.js

'use strict';
/* Controllers */

function PostListCtrl($scope, Posts) {
  $scope.posts = Posts.all();
  $scope.orderPost = 'name';
  $scope.query = '';

}

function PostDetailCtrl($scope, $routeParams, Posts) {
  $scope.post = Posts.get({phoneId: $routeParams.phoneId});
}

backend

PostApiController.java

@Controller
@RequestMapping(value = "/api/post")
public class PostApiController {
    @Autowired
    private PostRepository postRepository;

    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody List index() {
        List responseBody = new ArrayList();
        responseBody.addAll(postRepository.findByStatus(true));
        return responseBody;
    }

    @RequestMapping(value = "/{postId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody Post show(@PathVariable("postId") Long postId) {
        return postRepository.findOne(postId);
    }
}