In my previous post, I had started with the basics needed to
get an angular application running. Before we add more features let us
begin re factoring what we already have.
I've mentioned that our controllers are in the global scope. Let’s
fix that.
I am going to assign a value to the ng-app directive. So now
when you view the DOM through Firebug, you will notice one global variable
which is the app name we assigned to ng-app.
<html ng-app=”emailApp”>
We’re not done here. We need to register emailApp as an angular
module for it to work.
Create a new JS file called app.js, with this.
var emailApp = angular.module(‘emailApp’, []); //we have no dependencies as of now, hence the empty array.
We now need to map our controller(s) to this module. Let’s take
this opportunity to migrate the controller code from the html to its own file.
Create a new JS file called controllers.js, with this.
emailApp.controller('EmailCtrl', function($scope) {
$scope.messages
= [{
id:
0,
sender:
'jean@somecompany.com',
subject:
'Hi there, old friend',
date:
'Dec 7, 2013 12:32:00'
}, {
id:
1,
sender:
'maria@somecompany.com',
subject:
'Where did you leave my laptop?',
date:
'Dec 7, 2013 8:15:12'
}, {
id:
2,
sender:
'bill@somecompany.com',
subject:
'Lost python',
date:
'Dec 6, 2013 20:35:02'
}];
});
Now make sure to add app.js and controllers.js to the html
page. The screen should come up as before.
There’s no fun in displaying hardcoded data. Let’s ajax-ify
it.
To make use of ajax, we need to make use of an ajax service.
In angular, services are of 2 types built in and user defined. I will now make
use of the built in $http service to make ajax calls. User defined services
will be added soon.
Before getting started make sure to move the messages array
to a json file. I will save this json as messages.json
The controller now needs to have an extra parameter passed
in. That parameter is $http. $http will be injected into our controller by
angular. Our controller now looks like this,
emailApp.controller('EmailCtrl', function($scope, $http) { $http({method: 'GET', url: 'messages.json'}). success(function(data, status, headers, config) { $scope.messages = data; }). error(function(data, status, headers, config) { console.log("An error occurred. Please refresh.") }); });
For these changes to work, we need to run this app using a
web server.
Points to note
- It is recommended to maintain each controller in its own file, rather than using a single controllers.js
- Most built in services start with the $. It is recommended not to make use of $ for user defined services.
SPA features coming up in part 3.
No comments:
Post a Comment