Folks, I am using AngularJS and angular-resource to perform a pretty simple REST API call. Here is my JavaScript code for a page that lists (and creates) messages:
(function() {
'use strict';
var messagesApp = angular.module('messagesApp', ['ngResource']);
messagesApp.factory('Message', function($resource) {
return $resource('/api/messages/:id', {id: '@id'}, {
query: {method:'GET', isArray:true} });
});
messagesApp.controller('MessagesCtrl',
function($scope, Message) {
$scope.messages = Message.query();
$scope.addMessage = function() {
$.Dialog({
'title': 'Add new Message',
'content': '<p>Enter the <strong>unique</strong> name of the new message.</p><input type="text" id="newMessageName"/><p>Enter the <strong>unique</strong> ID for this message.</p><input type="text" id="newID"/>',
'draggable': false,
'overlay': true,
'closeButton': true,
'buttonsAlign': 'right',
'buttons': {
'save': {
'action' : function() {
var newMessage = new Message();
newMessage.name = $('#newMessageName').val()
newMessage.altid= parseInt($('#newID').val())
newMessage.longDescription = "This is a new message";
newMessage.$save();
console.log(newMessage.id)
}
}
}
});
}
}
);
})();
What happens is the console log message prints out 'undefined'. When I look at the network log, I see that my REST API is indeed returning the newly created object when it comes back.. Should I not be using Ok as a result type and instead use something else? Is there an HTTP header I'm missing .. or am I using the $save thing wrong??
The $.Dialog() method comes from another JavaScript library I'm using (metroui.og.ua) and I don't know if that's interfering with this or not..
newMessage.$save()
is asynchronous, so if you want to get a hold of the response data you should do it in the success callback function:See the docs