In MVC web programming server side controllers are responsible for reacting to an external stimulus (an HTTP request), and then building a model and possibly rendering a view in response to the stimulus. In a client app with AngularJS, the controller has an easier job.
AngularJS is officially a Model-View-Whatever framework, meaning there is quite a bit of flexibility in the architecture of an application. But, if you follow the typical conventions, a controller is simply a function the framework will call at the appropriate time. It’s the controller’s responsibility to put together a model by any means possible, and then the controller function is complete.
One notable difference between a controller in server side world of Rails or ASP.NET MVC and a controller with AngularJS is the view selection. Controllers and views are generally bound together on the client using directives (ng-controller) or in routing rules (a topic for a future post).
As an example, the following html is setting up the AboutController to manage the primary div element in the document. The primary div also contains some data binding expressions.
<body data-ng-app="patientApp"> <div data-ng-controller="AboutController"> <h3>{{message}}</h3> <div>Number of rabbits in the yard: {{rabbitCount}}</div> <button ng-click="increase()">More rabbits</button> <button ng-click="decrease()">Less rabbits</button> </div> <script src="libs/angular.js"></script> <script src="scripts/myScript.js"></script> </body>
When AngularJS takes control of the DOM it will see the ng-controller directive and go off searching for an AboutController. Here is one way to write the controller:
(function () { var AboutController = function($scope) { $scope.message = "Hello from the AboutController!"; $scope.rabbitCount = 2; $scope.increase = function() { $scope.rabbitCount *= $scope.rabbitCount; }; $scope.decrease = function() { $scope.rabbitCount -= 1; }; }; // Describe dependencies for the injector // in a minifier friendly way. AboutController.$inject = ["$scope"]; // Register the controller as part of a module. // The patientApp module will need to take a // dependency on patientApp.Controllers. angular.module("patientApp.Controllers") .controller("AboutController", AboutController); }());
Once AngularJS finds the controller, the framework invokes the function and injects any dependencies the controller requires. In this case the controller is simple and only requires a $scope dependency. We’ll talk about $scope in a future post, for now you can think of $scope as the model object you need to enhance for the application to work. The HTML contains data binding expressions like {{message}} and ng-click directives that will send the framework looking for functions to invoke named increase and decrease. These are all attributes the controller needs to provide on the $scope object.
In many respects the $scope object feels like a view model in an MVVM environment like Silverlight. The data binding expressions push and pull data into properties of the view model. The command type bindings, like ng-click=increase(), invoke methods on the view model. And the view model (a.k.a $scope object) behaves in true view model like fashion in the sense that it knows nothing about the view or the DOM. The view model only needs to change values internally and data binding takes care of the rest. Clean and testable.
From the Redis home page:
Redis is an advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.
Redis is also fast. Incredibly fast. Mind-numbing fast.
For more information, try the Redis docs or “The Little Redis Book” by Karl Seguin.
MSOpenTech just released a NuGet package of their Windows port to make it easy to download Redis and try the server from the command line. Combine this package with the ServiceStack.Redis package and it easy to be up and running quickly.
install-package redis-64 install-package servicestack.redis
The redis-64 package (for 64 bit systems) doesn’t add assembly references to a project, but does drop the Redis server executable in the packages\Redis-64.{version}\tools directory of the solution. Opening a command window and running redis-server.exe will launch the server with the default settings.
Here is a quick C# program to store and retrieve an object using the ServiceStack client:
static void Main(string[] args) { var client = new RedisClient("localhost"); var patientClient = client.As<Patient>(); var patient = new Patient { Name = "Scott", Codes = new List<string> {"1.1", "2.2"} }; patient.Id = patientClient.GetNextSequence(); patientClient.Store(patient); var retrievedPatient = patientClient.GetById(patient.Id); Console.WriteLine("{0}:{1}", retrievedPatient.Id, retrievedPatient.Name); }
Once the program runs, you can also go to the command line client in the tools directory (redis-cli.exe), and verify the data stored inside of Redis. Here is a shot of the cli client and server running:
Now that we know a bit about how modules work at an API level, we can look at questions that will be asked more than once in the lifetime of a project, like when to create a module, how many modules to create, and how to organize source code files for a module.
One thing to recognize early on is how much flexibility is available. Although the term "module" sounds like the JavaScript module design pattern (a single function inside a single file), there is nothing about an AngularJS module that requires all the code for a module to exist in a single file, or in a single function. Your code can use multiple JavaScript modules to add features to a single AngularJS module.
The code below is creating an alerter service to add to the patientApp.Services module, and could be one of many such pieces of code scattered across various files.
(function () { var alerter = function () { // ... }; angular.module("patientApp.Services") .factory("alerter", alerter); }());
Given this amount of flexibility, there are no real limitations on the number of modules and files you create.
Use an approach that causes the least amount of friction for you and the team. Factors to evaluate include the test and deployment strategy and the reusability of a module across multiple apps. Managing the dependencies of a large number of modules produces friction. Building large monolithic modules can also produce friction. Somewhere in between is a sweet spot.
There is already some good material out there on organizing file and modules.
The Angular Seed project recommends creating one module for controllers, one for directives, one for filters, and one for services. I'm not a fan of choosing this approach as a default.
Brian Ford has a post on Building Huuuuuuge Apps with AngularJS. Brian suggestion: "Each file should have one "thing" in it, where a "thing" is a controller, directive, filter, or service".
Cliff Meyers also believes in one thing per file in his post "Code Organization in Large AngularJS and JavaScript applications". I like that Cliff uses a dedicated folder for models instead of throwing in models with services or controllers.
Finally, Jim Lavin has "AngularJS Modules for Great Justice" and talks about the concepts of "package by layer" versus "package by feature".
One scenario I haven't found addressed very well is the scenario where multiple apps exist in the same greater web application and require some shared code on the client. I'll try to blog about this one in the future, but we'll visit some of the other AngularJS abstractions first.
People ask me what I do on a a regular basis. For this and various other reasons I'll shed some light on the current situation.
1.Medisolv is a company I've worked with in various roles for the last 10+ years. I'm now CTO, but still work with various product teams and commit production code as often as possible, which is by far finest part of the job. We will be hiring more software developers in the near future, so keep an eye out if you are interested.
2. Pluralsight is where I make glorious training videos. I'm currently working on a couple different courses and plan to finish "Learning To Program" in the next couple weeks. Making videos for Pluralsight is fun. Over the years I've collected 8 crystal microphones from Pluralsight as an award for making a Top 10 course. Occasionally I arrange them on the floor to recreate great naval battles from the 18th century. The photo to the right is the Battle of Valcour Island. You can see General Carleton advancing British warships towards the American's Congress and Royal Savage.
3. OdeToCode LLC is the company I own and operate for consulting services, but I've scaled back operations to simplify life and I am currently not taking on new work.
4. Workshops, Classes, and Conferences allow me to occasionally get out and see the world. I enjoy the classes I teach for DeveloperFocus and ProgramUtvikling and plan to update and revise my current curriculum to include topics like AngularJS and web service design with WebAPI. Conferences are fun, but also stressful and time consuming, so I'm cutting back. I will be at DevSum, NDC, and the fall DevIntersection this year.
And now, back to work…
Continuing from the last post, a module in AngularJS is a place where you can collect and organize components like controllers, services, directives, and filters. We'll talk about the "when & why" of creating a module in a later post. This post will focus on the API to create a module, and get a reference to an existing module. Stimulating topic, eh?
The proper way to create a module is to use the angular.module method passing at least the module name, and an array naming all the dependencies of the module (or an empty array if there are no dependencies).
angular.module("patientApp.Services", []); angular.module("patientApp.Controllers", []); angular.module("patientApp", ["patientApp.Services", "patientApp.Controllers"]);
The above code actually creates three modules – patientApp.Services, patientApp.Controllers, and a patientApp module that depends on the previous two modules. I like to have all this code centralized in one place for easy management.
The following code defines the three modules, then comes back and adds a "run block" to the patientApp module (a run block is a piece of code that Angular will invoke once the module is assembled and configured).
(function () { "use strict"; angular.module("patientApp.Services", []); angular.module("patientApp.Controllers", []); angular.module("patientApp", ["patientApp.Services", "patientApp.Controllers"]); var app = angular.module("patientApp"); app.run(["$rootScope", function ($rootScope) { $rootScope.patientAppVersion = "0.0.0.1"; }]); }());
Note the call to angular.module("patientApp") does not pass a second parameter with required module names, doing so would recreate the module and destroy anything already registered inside. Calling angular.module with just the module name will give you back a reference to an existing module so you can continue adding run blocks, services, directives, and other components into the module.
Somewhere else in the same file, or in a separate file, another block of JavaScript code might add an "alerter" service to the 'patientApp.Services' module (I know we haven't talked about services yet, but we will, and the short summary is that a service can carry out a specific task, like communicate over the network, and a service typically contains code you want isolated for testability or to obey the single responsibility principle).
(function () { var alerter = function () { return { alert: function (message) { // ... do something alerty } }; }; angular.module("patientApp.Services") .factory("alerter", alerter); }());
The API and terminology around services in Angular is unfortunately confusing and sometimes misleading, but we'll talk about that, too. For now, think of the factory method as "registering a service" in the module. The factory method is not providing a factory for the module itself, as the name might imply.
Yet another hunk of script from a different file can add a logger service to the same module.
(function() { var logger = function() { var log = function(message) { // .. do something loggy }; return { log: log, }; }; angular.module("patientApp.Services") .factory("logger", logger); }());
Of course, that could have all been combined together, if you so desire:
(function() { "use strict"; var alerter = function () { //... }; var logger = function() { //... }; angular.module("patientApp.Services") .factory("alerter", alerter) .factory("logger", logger); }());
Now that we understand a bit about how to create modules, we'll talk about the "when and why" in a future post.
One of the nice features of AngularJS is how the framework comes with a complete set of abstractions and features for building complex client pages from loosely structured and maintainable pieces of code. There are controllers, services, directives, data binding, and other pieces we'll continue looking at in future posts.
Angular also includes the concept of an application, which is the topic for this post.
An application is just an Angular module, which leads to a chicken and egg problem, since we haven't talked about modules, yet, but for now you can think of a module as an abstraction for packaging up related pieces of code.
For example, with Angular you can place all your controllers into a one module and all your services into a second module, or put the controllers and services all inside a single module. How many modules you define is entirely up to you and the needs of the project. Modules exist as containers that can provide configuration information, runtime dependencies, and other infrastructure support for their residents.
There are usually two features of the application module that make it "the application".
First is that the application module should know about all the other modules in the software, while those other modules might not know about each other or the application. Thus, the application module is the perfect place to bootstrap and glue together all the other components.
Secondly, the application module is the one identified by the ngApp directive. You can place this directive in the DOM using ng-app or data-ng-app attributes, as shown below in the simplest possible AnguarJS + HTML 5 page.
<!DOCTYPE html> <html> <head> <title>Patient Data</title> </head> <body data-ng-app="PatientApp"> <div> {{ patientAppVersion }} </div> <script src="libs/angular.js"></script> <script src="… my scripts …"></script> </body> </html>
You can have multiple applications inside a single page, but typically there will only be a single application and the ng-app directive will appear on the document's body element. After Angular loads and processes the HTML in the DOM, it will go looking for the "patientApp" module, so the following code is required:
(function () { "use strict"; var app = angular.module("PatientApp", []); app.run(function ($rootScope) { $rootScope.patientAppVersion = "0.0.0.1"; }); }());
angular.module is the API to use for creating and configuring a module. The first parameter is the name of the module, the 2nd parameter describes the other modules this module depends on (there currently are none).
The .run method will give Angular a function to execute after all the modules are loaded and the dependencies are resolved. In this sample, we'll add a property to $rootScope, which is the scope in use in the previous HTML (since we have no controllers yet). The magic of {{ data binding }} allows the web page to display the text "0.0.0.1".
You can reference the patientApp module from other JavaScript files using angular.module. The following code block could live in a separate .js file, and demonstrates how different pieces of code could be tied together to execute during the application bootstrap phase:
(function() { "use strict"; var app = angular.module("PatientApp"); app.run(["$rootScope", function($rootScope) { $rootScope.patientAppGreeting = "Hello!"; }]); }());
Note: the call to angular.module does not have a 2nd parameter (the list of dependencies) in this second block. The dependencies param should only appear once for a given module. Passing the dependencies parameter again will wipe out the module definition and start over.
Also note the second code block uses a style that is safe for minification because it passes $rootScope (a well known name to Angular) in an array along with the function to invoke during the run phase. Anytime you define a function where Angular will inject dependencies you are given the option of passing the function as the last element in an array that gives Angular the well known names of the dependencies required as arguments. We'll see more examples of this style as we move forward.
The one where I talk to Carl and Richard about everything from AngularJS, Durandal, and Glimpse to relationships and finding your true love.
Listen or download the show here.