Sunday, August 26, 2012

Angular.js for ajax CRUD

Its been a busy weekend, not in terms of coding though.  Just did some quick coding now.  This is now a book-markable ajax CRUD talking to conventional REST/JSON backend.

//app.js

angular.module('ratewatcher', ['ngResource']).
 config(function($routeProvider) {
  $routeProvider.
   when('/lenders', {controller:LenderListController, templateUrl:'lender-list.html'}).
   when('/lenders/new', {controller:LenderCreateController, templateUrl:'lender-detail.html'}).
   when('/lenders/:id', {controller:LenderEditController, templateUrl:'lender-detail.html'}).
   otherwise({redirectTo:'/lenders'});
 }).
 factory('Lender', function($resource) {
  return $resource('/lenders/:id', {id: '@id'}, {});
 });

//controllers.js

function LenderListController($scope, Lender) {
  $scope.lenders = Lender.query();
  
  $scope.remove = function(lender) {
   lender.$remove();
  }
}
  
function LenderCreateController($scope, Lender) {
  $scope.save = function() {
    var lender = new Lender({id: 0,
     name: $scope.lender.name, 
     category: $scope.lender.category, 
     url: $scope.lender.url
    });
    
    lender.$save();
  };
}

function LenderEditController($scope, $location, $routeParams, Lender) {
 $scope.lender = Lender.get({id: $routeParams.id});
 
  $scope.save = function() {
   $scope.lender.$save();
   $location.path('/');
  };
}

I thought the scala backend was really concise, but it turns you can also make the front end javascript just as concise.  Coupled with bootstrap css and basic html, this seems pretty good.

Suggested readings:
http://www.angularjs.org/ - Wire Up a Backend example
http://docs.angularjs.org/api/ngResource.$resource
http://jsfiddle.net/johnlindquist/qmNvq/
http://docs.angularjs.org/api/ng.$route

3 comments:

Oman said...

Thanks Jun I'm interested in seeing what the Scala backend looks like.

Jun Yamog said...

Hi Oman,

I used play. I don't have the code anymore but there is nothing special to make it angular.

http://www.playframework.com/documentation/2.1.0/ScalaJsonRequests

The only main difference is angular resource update by default uses POST. So you either change your play route to use POST instead of PUT. Or change angular resource to use PUT.

Oman said...

Thanks Jun you've inspired me to give Angular a go. I'm also going to try marry it with Bootstrap, which I believe should be fairly straightforward.