In the last post we didn’t introduce anything particularly new, instead we used what we already learned to add reply and forward functionality to the app. In terms of UI our app is now fairly complete. But before it can be a real app it has to be able to talk to a server to do the actual work of sending and storing emails. That’s what we’re going to do in this post.
Now the first thing I have to do is setup the server portion. I purposely left this post for last because I wanted you to be able to try out the Angular code without forcing you to setup a local development environment. Also I wanted it to be useful for everyone no matter what server technology they used – PHP, .NET, Node.js, etc.
Obviously I won’t be able to do that in this post. I can’t show you how to communicate with a server without a server, and that means I have to pick a technology. I’m going to use ASP.NET MVC. I will also do my best to describe the server portion in enough detail so that it’s also useful to everyone despite what server technology they use.
ASP.NET MVC Primer
A very quick primer for those not familiar with ASP.NET MVC. In this type of web application URLs are mapped to classes and methods. For example if a user entered the URL http://localhost/Home/Index
in their web browser that would trigger the method Index()
in the class HomeController
to run.
That method can choose whether to return data or HTML. The HTML is stored in a separate file referred to as a view. These views have the extension .cshtml
. Similar to the controller the proper view is selected based on the URL, once again for the URL http://localhost/Home/View
it will use the view stored in the folder \Views\Home\Index.cshtml
.
Of course I’m simplifying things, but this explanation should suit our purposes.
Back to the app
To start we need to create an ASP.NET MVC project in Visual Studio. I chose to start with an empty project and added a controller class called HomeController. And a action method called Index. In my view I include the CSS, JavaScript, and HTML from our last JSFiddle: http://jsfiddle.net/luisperezphd/n5AZk/
You can download this base project using this link: AngularWebApp1.zip
Now let’s update the app so that we get the email list from the server instead of hardcoding it in the JavaScript. First we’ll create the method on the ASP.NET controller:
public ActionResult GetEmails() { return Json(new[] { new { from = "Riker", to = "me", subject = "Nice to meet you, Pinocchio", date = "Jan 8", body = "That and helping Data finish 'Pop Goes the Weasel'. Also counts as a CMOH." }, new { from = "Picard", to = "me", subject = "I'm sorry, this is becoming a speech", date = "Jan 7", body = "But then I'm entitled, I'm the captain." }, new { from = "Data", to = "me", subject = "Could you please continue...", date = "Jan 6", body = "...the petty bickering? I find it most intriguing." }, new { from = "Troi", to = "me", subject = "But you spell knife with a 'k'", date = "Jan 5", body = "I spell 'knife' with an 'n', but then I never could spell." }, }); }
In this example we’re returning a static list of emails. We’re using the Json()
method to tell ASP.NET to return this data back to the browser as JSON.
Now we’re going to replace the hardcoded list in our JavaScript with a call to this action. The JavaScript is in the view along with our HTML (/Views/Home/Index.cshtml). So replace this:
$scope.emails = [ { from: 'John', to: 'me', subject: 'I love angular', date: 'Jan 1', body: 'hello world!' }, { from: 'Jack', to: 'me', subject: 'Angular and I are just friends', date: 'Feb 15', body: 'just kidding' }, { from: 'Ember', to: 'me', subject: 'I hate you Angular!', date: 'Dec 8', body: 'wassup dude' } ];
With this:
$http.post("/Home/GetEmails").then(function(response) { $scope.emails = response.data; });
Finally we need to add $http
as a parameter in our Angular controller, like we did with $scope
. So your controller method should be changed from this:
EmailController($scope)
to this:
EmailController($scope, $http)
That’s it, if you compile and run this you should see your email list change.
You can download the code here: AngularWebApp2.zip
Send Email
One down and one to go. Sending email is going to be very similar, the main difference is that we didn’t pass any data to GetEmails()
but we need to pass the email we’re sending to SendEmail()
.
This method is going to be simple. All the server is going to do is populate the date
and from
fields of the email and send that information back to Angular. To accomplish this we are going to need two things. We need to add an action to our ASP.NET controller and a C# class to hold the data Angular is sending.
Let’s start with the C# class. It should contain all the same fields found in the JavaScript code. For our purposes you can put this class anywhere. In order to simplify things and keep all the code in one place I’m adding it as a nested class inside the controller:
public class ComposeEmail { public string from { get; set; } public string to { get; set; } public string subject { get; set; } public string date { get; set; } public string body { get; set; } }
Now for the ASP.NET action method itself:
public ActionResult SendEmail(ComposeEmail composeEmail) { composeEmail.from = "me"; composeEmail.date = DateTime.Now.ToString("MMM d"); return Json(composeEmail); }
Finally the call from Angular. Change the sendEmail()
method from this:
$scope.sendEmail = function () { $scope.isComposePopupVisible = false; $scope.composeEmail.from = "me"; $scope.composeEmail.date = new Date(); $scope.sentEmails.splice(0, 0, $scope.composeEmail); };
To this:
$scope.sendEmail = function () { $http.post("/Home/SendEmail", $scope.composeEmail).then(function (response) { $scope.isComposePopupVisible = false; $scope.composeEmail = response.data; $scope.sentEmails.splice(0, 0, $scope.composeEmail); }); };
That’s it! If you run your code now, send an email and check the “Sent” tab you will see that the date is populated. If you click to open that email you will see that the “from” field is populated as well.
Download the complete source here: AngularWebApp3.zip
This covers the essentials of AngularJS and everything you need to create a functional web application. In this series you created a fairly elaborate UI with multiple screens that update dynamically. To make it functional you communicated with a backend server to do the work.
This brings us to the end of this blog series on building an email web app using AngularJS. Please use the comments below to let me know what you think.
In this blog series we’ve covered enough to build an application using AngularJS. We’re just scratching the surface of what AngularJS has to offer. In subsequent posts I dig deeper into AngularJS, including how to create more complex applications and UIs, how to use and create your own reusable components, how to structure and test your code so that it easy to maintain as your application grows.
Luis Perez says
If you are interested in more practical AngularJS examples I recommend taking a look at the following post by Dave Kerr: http://www.dwmkerr.com/practical-angularjs/part-1-introducing-angularjs/
Guillaume says
Interesting post !
But I have few questions :
– Why don’t you use a ASP.NET WebApi Controller ?
– It isn’t better to use a GET method for the Action ? And prefer $http.get than $http.post on the Angular side ?
Regards,
Guillaume
Ming says
Great
Benjamin Wheeler says
Wow, read the whole thing. Terrifically helpful, most comprehensible introduction I’ve seen. Many concepts clicked for me here that haven’t before.
Shree J says
Really nice tutorials! Thanks a lot for spending time and effort to do this!
Kiru says
Awesome tutorial to start with. Thank you
global says
What a wonderful explanation!!!
Flow is very well written , and the concepts are very well explained .
I liked the way you add a feature and explain the angular. super!!!
Sherry says
It seems like it is an old post but it is still helping me in 2017.
Thanks, my first AngularJS lesson, really clear explanation.
Abhishek Kumar says
Comprehensive guide to learn Angular JS as a newbie, great methodology of introducing each concept; overall a great place to get going with Angular JS.
Thanks a lot Luiz for this blog :)