Your First AngularJS App: Getting the Data via Ajax

The last change I am going to make is to obtain the to-do list data as JSON data via an Ajax request. (I describe JSON in Chapter 5 if you are unfamiliar with it.) I created a file called todo.json in the angularjs folder; you can see the contents in Listing 2-13.

Listing2-13. The Contents of the todo.json File

[{ “action”: “Buy Flowers”, “done”: false },

{ “action”: “Get Shoes”, “done”: false },

{ “action”: “Collect Tickets”, “done”: true },

{ “action”: “Call Joe”, “done”: false }]

As you can see, the JSON data format is similar to the way that literal JavaScript objects are declared, which is one of the reasons why JSON is a dominant data format for web apps. In Listing 2-14, you can see the changes that I made to the todo.html file to load the data from the todo.json file rather than using a locally declared array.

Listing2-14. Making an Ajax Call for JSON Data in the todo.html File

<script>

var model = {

user: “Adam”

};

var todoApp = angular.module(“todoApp”, []);

todoApp.run(function ($http) {

$http.get(“todo.json”).success(function (data) {

model.items = data;

});

));

todoApp.filter(“checkedItems”, function () {

return function (items, showComplete) {

var resultArr = [];

angular.forEach(items, function (item) {

if (item.done == false || showComplete == true) {

resultArr.push(item);

}

});

return resultArr;

}

});

todoApp.controller(“ToDoCtrl”, function ($scope) {

$scope.todo = model;

$scope.incompleteCount = function () {

var count = 0;

angular.forEach($scope.todo.items, function (item) {

if (!item.done) { count++ }

});

return count;

}

$scope.warningLevel = function () {

return $scope.incompleteCount() < 3 ? “label-success” : “label-warning”;

}

$scope.addNewItem = function(actionText) {

$scope.todo.items.push({ action: actionText, done: false});

}

});

</script>

I removed the items array from the statically defined data model and added a call to the run method defined by the AngularJS module object. The run method takes a function that is executed once AngularJS has performed its initial setup and is used for one-off tasks.

I specified the $http argument for the function I passed to the run method, which tells AngularJS I want to use the service object that provides support for making Ajax calls. Using arguments to tell AngularJS what features you require is part of an approach known as dependency injection, which I describe in Chapter 9.

The $http service provides access to low-level Ajax requests. Low-level in this case really isn’t that low at all, until compared with the $resources service that is used to interact with RESTful web services. (I describe REST in Chapter 3 and the $resource service object in Chapter 21.) I use the $http.get method to make an HTTP GET request to the server for the todo.json file:

$http.get(“todo.json”).success(function (data) {

model.items = data;

});

The result from the get method is a promise, which is an object used to represent work that will complete in the future. I explain how promises work in Chapter 5 and get into the detail in Chapter 20, but for this chapter it is enough to know that calling the success method on the promise object lets me specify a function that will be invoked when the Ajax request to the server has completed and that the JSON data retrieved from the server will be parsed to create a JavaScript object and passed to my success function as the data argument. I take the data I receive and use it to update the model:

$http.get(“todo.json”).success(function (data) {

model.items = data;

});

You won’t notice any difference if you navigate to the todo.html file with the browser, but the data is being obtained from the server using a second HTTP request. You can see this using the F12 tools to report on network connections, as shown in Figure 2-11.

The fact that I have to check the browser to prove that Ajax is being used demonstrates just how easy AngularJS makes it to work with remote files and data. This is a theme I will be returning to throughout the book because it underpins a lot of the features that AngularJS provides for creating more complex web apps.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

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