A simple one-page static Angular.js application with AJAX

After a lot of research and experimentation, I’ve decided to bite the bullet and learn to use Angular.js and then connect it to the .NET MVC Web API. I found many of the tutorials out there to be unusually frustrating. There is no end to people complaining about the Angular documentation and their howls are justified. The official tutorial is especially vague and convoluted. It tries to do way too much stuff at once with little explanation of what is going on. It also spreads all the code out between many files. Of course this is how you should organize a real application, but I want to see what I’m doing on one screen so I can easily detect typos and relationships. I decided to try and eliminate as many variables as possible and build a simple static site (no dynamic back-end server language) that:

1. Display a simple message on the screen.

2. On an event generated by the user, change the messages using Angular’s two-way binding.

3. Made an AJAX call to a remote web service (a static dummy one in this case) and set the message to the response received.

If it can do all that, it’s a long way toward doing a lot more. For newbie’s, how can this be demonstrated with the fewest lines of code? I aimed to find out. Here is what I came up with.

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <title>Angular.js Static Demo</title>
    <script src="angular.js"></script>
</head>
<body ng-controller="messageController">
    Hello, here is a message:<br />
    {{message}}

    <br /><br />
    <button ng-click="simpleChange();">Update message with two-way binding javascript.</button><br />
    <button ng-click="ajaxChange();">Update message with two-way binding and an ajax call.</button>

    <script type="text/javascript">
        var myApp = angular.module('myApp', []);
        
        myApp.controller('messageController', function ($scope, $http) {

            $scope.message = 'Initial message!';

            $scope.simpleChange = function () {
                $scope.message = "Message changed!";
            };

            $scope.ajaxChange = function () {
                $http.get('message.html', {})
                .then(function (data, status, headers, config) {
                    $scope.message = data.data;
                });
            };
        });

    </script>
</body>
</html>

A few comments:

Note the ng-whatever properties in the html and body tags. They are called directives and these are what trigger the initializations. {{message}} is the dynamic piece that we will be automatically updating.

Surprisingly little is needed in the end, though it took me a while to get here. Many examples of controller initialization out there neglected to include $http as a parameter. If you leave it out, then calls to $http fail silently – the worst sort of error of all. There are also syntax changes between the latest version of Angular and it’s state from a year ago. About half the answers I came across on Stack Overflow had recent comments complaining about how a particular snippet doesn’t work anymore. Ugg.

Notice that onClick events are replaced with ng-click so that Angular can include it’s secret sauce in the call.

If you were calling that ajax url with jquery the “data” variable would be all you need. But, because Angular turns everything into JSON automatically (which is actually really great), you need “data.data” to get to the meat of the response. The file message.html is a plain text file (no HTML tags) containing one line of text.

That’s it – that’s all you need! You don’t need to define a bunch of models or resources or “promises” or anything else – not right away at least.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>