Created
July 8, 2012 02:36
-
-
Save victorbstan/3069059 to your computer and use it in GitHub Desktop.
AngularJS vs JQuery for basic GET POST AJAX API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var DOMAIN = 'http://localhost' | |
var PORT = 3000; | |
var DATA_SOURCE = '/clips.json'; | |
// ANGULAR | |
function clips_controller($scope, $http) { | |
$scope.clips = []; | |
// get the data from the API backend | |
$http.get(DOMAIN+":"+PORT+DATA_SOURCE).success(function(data) { | |
$scope.clips = data; | |
}); | |
// add new data to the view and post it to the API backend | |
$scope.add_clip = function(){ | |
$scope.clips.unshift({body:$scope.new_clip}); | |
$http.post(DOMAIN+":"+PORT+DATA_SOURCE, {clip:{body:$scope.new_clip}}); | |
}; | |
}; | |
// JQUERY | |
/* | |
jQuery(document).ready(function($) { | |
$clip_latest_el = $('#clip-latest'); | |
// get data | |
var update_list = function(){ | |
$.ajax({ | |
url: DOMAIN+":"+PORT+"/clips.json", | |
success: function(data) { | |
console.log(data); | |
$.each(data, function(i,v){ | |
// limit to 5 items | |
if(i==5) { | |
return false; | |
} | |
console.log(v.body); | |
// replace placeholder on first item... | |
if(i==0){ | |
$clip_latest_el.html(v.body); | |
} else { | |
// then append values... | |
$clip_latest_el.append("<hr>"+v.body); | |
} | |
}); | |
} | |
}); | |
}; | |
update_list(); | |
// submit form data | |
$("#clip-form").submit(function(){ | |
console.log($(this).serializeArray()); | |
var body_form_data = $(this).serializeArray()[0].value; | |
$.ajax({ | |
type: "POST", | |
url: DOMAIN+":"+PORT+"/clips.json", | |
data: { | |
clip: {body: body_form_data} | |
}, | |
dataType: "json", | |
success: function(data) { | |
// append the newly created resource to the list | |
$clip_latest_el.prepend(data.body+"<hr>"); | |
} | |
}); | |
return false; | |
}); | |
// update list on request | |
$("#update-list").click(function(){ | |
update_list(); | |
}); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment