Friday, January 17, 2014

ngConf Report: Day 2 of Angular Goodness

Yesterday was a fantastic day. I spent the afternoon helping out at the Wintellect booth. There is a rumor I may have been seen challenging attendees to a game of 9-ball in the game room once or twice. I also attended two great sessions, one about dependency injection and the other a panel discussion.

The sessions from day one are now posted online.

The Future of Dependency Injection

This talk by Vojta Jina discussed dependency injection within Angular and what the future will look like. First, he talked a bit about why DI is so important. I think this is something many server-side OO developers take for granted but the nature of JavaScript makes it a little less obvious on the client. He demonstrated the difference between creating instances from within a module versus taking them as a constructor panel, but pointed out this leads to a monolithic and complex “main method” that has to wire everything up. The logical solution is an injector that can keep track of components and provide them as needed when other components require them.

The existing Angular 1.x versions use a module-based approach. Each module is essentially a separate DI container, and modules can depend on other modules so the injector knows how to reach across containers to wire up the dependency graph. This approach works but is also a bit complex to understand and master. The Angular team decided they wanted to focus on simplifying this as much as possible for the 2.x versions, so a new approach is being taken.

The new approach is quite elegant. The concept of containers goes away. This is possible because of the way you reference dependencies. There are two parts. The first is a special statement to import dependencies, that looks something like this:

import {MyComponent} from ‘./myComponent’;

This will look in the myComponent.js file for the definition (either via constructor function or factory) of MyComponent. Anything you wish to expose for dependencies gets exported in a format similar to TypeScript, like this:

export class MyComponent

Of course this is the new format that is not compatible with older JavaScript implementations. For this, Google provides a compiler that builds modern JavaScript out of “future JavaScript” or you can use the direct convention like:

define([‘./myComponent’, function ….

Then to annotate what dependencies a class needs, you annotate like this:

class MyDependentComponent {

or the classic:

myDependentComponent.annotations = new Inject(MyComponent);

This is very exciting. It allows for asynchronous dependency resolution and makes asynchronous module loading a first class citizen of the framework. As a veteran of many server-side DI frameworks over the years I’m a huge fan of the changes they are making and look forward to the new version.

Team Panel

The afternoon concluded with a team panel. This included almost a dozen team members answering questions that had been voted on a site. The majority of questions had been previously answered in other talks. A few that stood out included a concern over Dart support. There had been some rumors that the adoption of Dart would de-prioritized JavaScript but the team assured everyone that JavaScript will continue to be first class.

One interesting question was about memory leaks. The team was adamant that Angular is so thoroughly tested that it simply doesn’t leak, but that there are side effects from practices that can cause the leaks. For example, compiling a DOM element and not attaching it to the DOM will cause a leak. We’ve encountered issues with third party controls that create or track DOM elements as well, but in each case we’ve simply had to track the integration point and either call $destroy on the related $scope or call a method on the third-party control to detach the DOM. Angular automatically fires an event when a compiled DOM node is detached that will destroy the associated $scope.


Igor Minar started day two by talking about the Angular community. He explained the vision of changing the way developers feel about the web, and how users experience the web. He shared stories about the early days of Angular when there were few defects and fewer docs. He covered many of the ups and downs, like the 1.2 release breaking a lot of apps until they reverted a “minor” change, the reaction when they pulled support for IE8 and the announcements around Angular for Dart. He also shared how the team uses the leading edge version of Angular internally … literally within hours of a release, hundreds of apps within Google are updated with that version. This has taught them to focus on the stability of changes and “not to ship bugs.” The pre-release builds are pushed to Bower as well.

Pro tip: when building features like progress bars, date controls, etc. instead of building them as an Angular directive, consider building them as a traditional reusable JavaScript entity and then use the directive to glue into Angular. Makes more more reusable code.

At the end of his talk he shared that the team is creating an Angular working group to help steer the direction of future releases. Do you want to contribute to Angular and help it grow? The call to action is available right here.


The next talk covered TypeScript. This is a language Wintellect has had great success using. It is not a separate language to learn, but is a superset of existing JavaScript that tries to conform with upcoming ECMAScript 6 standards. Sean Hess walked through some examples and features of the language. We have experience with several projects that use TypeScript, including projects that switched midstream so we have a great before/after snapshot of the benefits it provided (and surprisingly, even the “JavaScript purists” on the team were won over). Contact me or swing by the Wintellect booth if you want to learn more.

Realtime Apps with Firebase

Anant Narayanan covered Firebase. He started with a discussion of the evolution of web apps and the notion that we are finally at a place with tools like Angular to build real web apps and not just try to paste the app paradigm onto the web page paradigm. Firebase is an API (on top of an application platform) to store and synchronize data in real time. It provides a simple login service that supports several major login providers for authentication and provides a declarative security system for data. Firebase provides “3-way data-binding” by synchronizing data with remote databases for you.

He demonstrated the functionality by building a live “video commenting” app. The concept is that while you are on the page, the comments update real-time as other users are adding comments. It was very impressive to see how easily he was able to drop in the $firebase dependency and create a real-time app on the fly. Firebase provides a hosting service for SPA apps that holds all static assets, JavaScript, etc. Learn more on their site. You can also interact with a sample he built and deployed live.

Scaling Directives

Burke Holland talked about scaling directives. He first covered the history of KendoUI and how once they released it, they went through a phase of various requests that centered around Knockout, leading them to build a Knockout integration. Suddenly in 2013 these requests started shifting to Angular. Burke was given the task of integrating KendoUI to Angular. It was interesting to learn about his approach to this integration and what he learned along the way.

Their approach is interesting. They have a “master directive” that spins through all of the available widgets, then creates a new directive per widget. It binds to the various attributes, and most importantly wires changes to the $scope through the “Change” and “Value” events that exist on every widget. For the more complex widgets they create special one-off directives to handle the complexity (such as their Scheduler). 


I was not able to sit in on the Zone talk as I was invited to a panel interview with Ward Bell, John Papa, and Dan Wahlin to discuss Angular as it relates to the .NET community. The ZoneJS library is “thread-local storage for JavaScript VMs” that provides “execution contexts” to persist across asynchronous calls. I probably am not doing it justice so be sure to check out the video that is already posted online.

Using Angular with Require

Thomas Burleson took the stage to discuss using Angular with Require. He summarized at a high level that Angular injects instances and Require injects classes.

There are 4 general dependency types: load, construction, runtime, and module. Require provides a package dependency manager, a class injector, a JavaScript file loader, and a process to concatenate JavaScript.

Require has three methods: define (define your dependencies and register a factory) using the AMD (Asynchronous Module Definitions) standard, require (callback function invoked when dependencies are resolved), and config to configure source paths and aliases. He did a great job of showing not only how Angular and Require solve different problems, but how they can work together right now.

The talk is posted online here.

He did not have time for the Angular decorator talk, but posted his slides here.

End to End Testing Using Protractor

Julie Ralph discussed end-to-end (E2E) testing with Protractor. Her words: “Shiny new …” She is a software engineer in test at Google. It replaces the Angular Scenario Runner. Test is about confidence in code. Julie says if you give her a suite of unit tests she will not have confidence your system is going to run … they are a good foundation but you need a good set of E2E tests. Protractor uses WebDriver (also known as Selenium). The framework is specific to Angular, because it can use the knowledge of Angular to make it easier to write tests.

Common complaints about E2E: tests are hard to write, they are tough to keep up to date, they are slow and flaky, and it’s tough to debug them (not to mention authentication and cleaning up after tests). Protractor helps by providing a manager to keep WebDriver running and up to date. Protractor uses Jasmine to scaffold tests and a similar configuration to Karma. It also provides some special helpers for interacting with the browser and DOM.

Nice “wait for Angular’ function that will let injection and asynchronous code to complete before continuing your test. In the future, the framework will formalize the contract with Angular and migrate internal tests away from the scenario builder.


Jason Aden then discussed ng-model. It is core to great UI components and responsible for 2-way data-binding. It can be used to port jQuery components and enables declarative components. To add this in you use an ng-model in your directive and require it as part of the directive definition.

It interfaces with ng-form to transport input into a model representation. It takes care of alerting listeners. It watches for model changes and changes model representation back to view representations. In short, it is the key “glue” for data-binding.


There is more to come but I probably won’t have to time to wrap up before I post so I figured I would close out here. This conference has made it clear that Angular is a force to be reckoned with and is not only gaining attention, but is being used in real world applications with success. The community is excited and supportive and the releases are coming quickly. The conference was incredibly well-organized and an absolute pleasure to attend. I’m looking forward to watching this community grow over the next year and to future events.

Thanks to all of the organizers and sponsors, and of course to the community for helping make this a great set of tools (I know people feel the favor is returned because of what it saves them when building JavaScript apps). Don’t forget the videos are all available online.

Thursday, January 16, 2014

ngConf Report: Day 1

The world’s first public Angular conference kicked off today in Salt Lake City and I was excited to attend with Wintellect. Our company has been using Angular along with other tools like TypeScript to build enterprise apps scaled across large development teams for a year now, and were able to bring most of the team who has been hands-on with this toolset to the conference. It was a great day interacting with a massive community who are building apps in every vertical. In this post I want to share some of the highlights from the conference.

Keynote – History of Angular

The keynote was kicked off by creator and original contributor Miško Hevery and Brad Green. They started by sharing some of the history for Angular. I’ve been sharing that I feel one of the powerful features of angular is the developer/designer workflow. It enables the XAML-style workflow many C# developers are used to in pure HTML scenarios. This was reinforced in the keynote when they mentioned the original Angular was written to make things easier for designers and non-programmers rather than developers. It of course grew from there over time, but the initial view was a sort of advanced spreadsheet for the cloud The first test of Angular was internal at Google. An existing application had been built over 6 months and contained 17,000 lines of code. Miško offered to take this on and in weeks was able to recreate the app using Angular and simplified it to 1,500 LOC. The benefits they found mirror what Wintellect has experience: faster production of code, improved quality, easier readability, better designer/developer workflow and testable, modular code that scales across teams. To give you an idea of how much the framework has grown, there are now over 600 contributors and the project receives 10 – 15 pull requests per day. They also shared their keynote slides.

Future of Angular 2.0

The goal for Angular 1.0 was to provide support for the browsers of yesterday. The upcoming 2.0 release will be focused on the browsers of tomorrow. This includes several features that were covered at a high level in the keynote, including:
  • A new benchmarking framework
  • Lazy loading for dependency inject and support for  ECMAScript 6
  • Faster change detection, taking advantage of Object.observe when possible
  • Better poly-fills
  • Improved support for mobile
    • Built-in offline support
    • Active animations
    • Reduction of initial load time
    • Faster performance
    • The team will also build a flagship app for mobile
  • Reduce API complexity
    • Simplify directives
    • Dependency injection
    • More declarative code with type and data annotations
  • Support for ECMAScript 6
    • Classes
    • Modules
    • Annotations
  • Support for Standard widget libraries
    • Shadow DOM
    • DOM Mutation observers
    • Object.observe
  • Improved debugging
    • Interoperability with zone.js that will allow elimination of need for $digest and $apply
    • Interoperability with diary.js

AngularJS in 20 Minutes

Dan Wahlin gave a great overview of what Angular is in 20 minutes. Kudos to him for building a tiny app live in front of the group. He focused on the essentials: data-binding, directives, filters, modules, controllers, routes, animations, etc. In just a few minutes he demonstrated the power of Angular by creating an app that held a list of customers in memory and provided a search filter to select customers that matched text input by the user. It is a testament to how powerful and flexible the framework is that he was able to wire this up without writing a line of code in the beginning.

Building Massive Angular Apps: DoubleClick

The next panel discussed what it took to build a massive application using Angular. I was very intrigued by this because we are also currently working on a huge enterprise app. The team indicated their app was on the framework they believe the longest (they started very early) and possibly the largest (right now it looks like ours might be larger). The app is the DoubleClick Campaign Manager (DCM) and is used by publishers to upload and track their ad campaigns. The project started using Angular in November of 2010 (we started in early 2013). They have over 20 JavaScript engineers, 71,000 lines of JavaScript, 133,000 lines of unit test code, 26,000 lines of markup, 129 controllers, 137 directives, and 59 services. By just the service and controller app, one of our projects is actually larger than this.
The first thing they discussed was authorization and activation with a user profile. They need to get the user profile information into the app and reduce the overhead of doing this with every call. Their solution was to render the information on the server, pull it into Angular using the copy service and declare it as a constant to reference anywhere. They then implemented conditional feature loaded by extended the HTML with attributes that essentially mark up what features can be turned on or off. If the user doesn’t have the feature, that DOM Node is removed which takes it a step beyond just “show” and “hide.”
The next section was about code organization. I was happy to see we independently came up with the same best practices their team was using – things like preferring composition over inheritance, using mix-ins but only sparingly (using Angular’s extend), but most importantly favoring Angular services. This is where our app has the most mileage for reuse and simplifying controllers, by taking well-defined actions or processes and placing them in services that can be shared across controllers.
They next mentioned how to use services to extend the Angular built-in services. Again, this mirrored a solution we came up with. We extended the $http service, they chose to do it with the $resource service. They exposed a fluent interface to configure the service and extended it to return actual objects and not just $http promises. We provide services that implement a base class to wrap $http that does custom error handling among other things, then returns first class entities based on the nature of the request, like musicService.getSong(“lullabye”).then(function(song) { song.sing(); }
The slides from the presentation are shared here.


The next talk covered promises. What was unique about this talk was that he covered how promises aren’t just for asynchronous processes, but really designed to handle uncertainty and wrap your brain around unpredictable processes. He mentioned how callbacks were the initial approach to asynchronous tasks that don’t block I/O, but fall short because they are complex and require heavy nesting.
Promises address this through a common API that modules can agree. They don’t just replace callbacks, but create rich functionality around them. A great example is the example that you can run three processes in parallel and use $q.all to run only when the three other promises completed.
Christian Lilly suggested several steps to getting familiar with the promises ($q) API in Angular. Step one? Consume existing promises by using services like $http. Step two? Start using $resource. Step three is to use the $routeProvider and familiarize yourself with $route: resolve that enables deferred rendering until a promise is completed. The final step is to recognize that Angular no longer unwraps promises in views. It was too much magic so the wizards destroyed the scrolls. Step five was to start creating your own promises using the $q service. Step six is to use third-party libraries that take advantage of promises such as Angular.UI. Step seven is to create a lazy promise by wrapping a promise in a service. Step eight is to learn about interceptors in the $http lifecycle.

Advanced Custom Directives

Dave Smith gave a very informative and entertaining talk about custom directives. A few tip he provided:
  • Use a unique prefix (don’t clash with others and make it easier for readers to identify)
  • DON’T use ng-
  • Common convention is two letters – that’s 1,296 possibilities
He did prefix the talk with a great bad joke that only makes sense if you are familiar with custom directives: What did the directive say after getting cut out of its parents’ will? I’m isolated.
A great way to learn about directives is to read the Angular source code to see how they implemented their own directives.
Use directives when you want a reusable HTML component, a reusable HTML behavior, you want to wrap a jQuery plug-in and almost any time you need to interface with the DOM.
He recommended the practice of placing directives in their own module. This allows you to unit test them independent of the rest of the application (of course you need to pull it in as a dependency for your main app). Another suggestion is to include a  script tag of type text/ng-template with an id equal to the URL of the directive. This will pull the directive in once and cache it.
He shared various ways to build behaviors, custom HTML and even widgets using directives and covered scope isolation as well. He noted how you can use attributes to pass data that are outside of the $digest loop and don’t require creating a new $scope. Use $eval to pull in the attribute values and $set to set a new value on the attribute.
Link is used for the initial pass of rendering the directive. If you need to manipulate DOM after link time or reuse a template multiple times, you need a compile function.
Great description of transclusion: it is a “picture frame” for content. You either sell the frame with your picture inside, or you sell the frame and allow consumers to put their own content inside. Slides from the talk are posted here.
On that the morning session wrapped. So far this has been a terrific conference!

Monday, January 13, 2014

Interception using Decorator and Lazy Loading with AngularJS

Angular provides it’s own dependency injection that supports everything from annotations to decorators. Interception is a feature that allows you to extend, intercept, or otherwise manipulate existing services. It makes it easy to monkey-patch existing APIs to suite the specific needs of your application. You can build an app that relies on the built-in services for common functionality such as logging and still apply your own custom behavior as needed.

To illustrate this, consider a simple Angular app. The markup simply displays a title:

<div data-ng-app="myApp">
    <div data-ng-controller='MyController'>{{title}}</div>     

The controller is a bit more interesting because it configures the title and then logs a few messages to the console. By default, Angular’s $log service provides a safe way to log information to the browser’s console. I say “safe” because it will check if the console is present before attempting to use it so you won’t throw exceptions on older browsers. Let’s look at  a simple controller that is injected its $scope to set up the title and the $log service to log a warning and an error. Notice how the service uses the $injector property (array) to annotate its dependencies – you can verify this by changing the name of the constructor parameters to see they will still be injected correctly.
var MyController = (function () {
    function MyController($scope, $log) {
        this.$scope = $scope;
        this.$log = $log;
        $scope.title = 'Decorator example';
        $log.warn('This is a warning.');
        $log.error('This is an error.');
    MyController.$injector = ['$scope', '$log'];
    return MyController;

Wiring up the app is then simple:

var app = angular.module('myApp', []);
app.controller('MyController', MyController);

When you run the app in a browser with the console open, you’ll see the warning and error written to the console:


Of course, some systems may wish to capture errors and warnings in a different way. You may want to present a debug console to the user regardless of the browser they are in, or even wire up a service that can record exceptions on the server. Either way, instead of writing your own logging service, you can use Angular’s decorator to monkey-patch the $log service and extend it with your own functionality. This supports the open/closed principle, to keep your components open to extension but closed to direct modification. 

First I’ll extend the markup to provide a console area. I wouldn’t normally do this using the $rootScope but it will keep the example simple. It also shows how we can set up a global area outside of any of the controllers:

<div data-ng-app="myApp">
    <div data-ng-controller='MyController'>{{title}}</div>    <hr />
    <div data-ng-repeat="line in console">

Now let’s create a service that simply picks up anything generated as a warning or an error and keeps track of it. (If you wanted to, you could take what I wrote about providers in my last post and use that to configure how much history the service keeps).

var MyConsole = (function () {
    function MyConsole() {
        this.lines = [];
        this.writeLn = this.pushFn;
    MyConsole.prototype.pushFn = function (message) {
    return MyConsole;
Notice this simply tracks an array internally and exposes a method to write to it. By itself, it won’t do much good because there is no way to see what’s actually being written. In the HTML we’re expecting something called console that contains a collection. Normally you’d wire this in your app’s run section or similar, but for fun let’s have the service itself set up the root scope. The problem is that in using the service to monkey-patch the logger, we’ll have to instantiate it before the $rootScope is created by Angular. If we try to inject it as a dependency, we’ll get an exception. To fix this, we’ll keep track of whether we have the root scope or not, and ask the $injector if it is a available. Here is the updated service:

var MyConsole = (function () {
    function MyConsole($injector) {
        this.lines = [];
        this.rootScope = false;
        this.writeLn = this.lazyRootCheckFn;
        this.injector = $injector;
    MyConsole.prototype.pushFn = function (message) {
    MyConsole.prototype.lazyRootCheckFn = function (message) {
        if (!this.rootScope && this.injector.has('$rootScope')) {
            this.rootScope = true;
            this.injector.get('$rootScope').console = this.lines;
            this.writeLn = this.pushFn;
    MyConsole.$inject = ['$injector'];
    return MyConsole;

Notice that there are two internal functions that can be exposed as the outer writeLn function. At first, a function called lazyRootCheckFn that checks for the $rootScope is wired in. It asks the $injector if it has the $rootScope yet, and when it does, wires it up. It then swaps the external function with the simpler function called pushFn that simply adds the message to the list. This prevents it from checking again every time it is called because the $rootScope wire-up is a one-time event. This is also how you can lazy-load dependencies when they are not available to your app, because the $injector is the first thing Angular wires up as it handles everything else and allows you to query whether something has been configured yet using the has function. Now the console on the root scope is wired to the collection of messages and ready for data-binding. Of course, you won’t see anything yet because the logger needs to be intercepted.

To intercept a service, request the $provide service during your app’s configuration:

    '$provide', function ($provide) {

This service exposes a function named decorator that allows you to intercept a service. You pass the decorator the service you wish to intercept, then an annotated function that you use for decoration. That function should request a dependency named $delegate. The $delegate dependency passed in is the service you wish to intercept (in this case, the $log service). At the end of the function, you return the service to take it’s place. You could return an entirely new service that mimics the API of the original, or in the case of our example simply monkey-patch the existing service and return it “as is.” Here I just return the original service:

$provide.decorator('$log', [
function ($delegate, myConsole) {
    return $delegate; // this is the $log service

I want to intercept calls to warn and error, so I created a function to reuse for patching:

var swap = function (originalFn) {
    return function () {
        var args = [];
        angular.forEach(args, function (value, index) {
        originalFn.apply(null, args);


The function returns a new function that effectively parses out the arguments into an array, sends them to my own version of the console service, then calls the original function with the arguments list. Now I can monkey-patch the existing methods to call my own:

$delegate.warn = swap($delegate.warn);
$delegate.error = swap($delegate.error);

That’s it! My controller has no clue anything changed and is still faithfully calling the $log service. However, as a result of intercepting that service and adding a call to myConsole, and the fact that myConsole lazy-loads the $rootScope and wires up, it now will display errors and warnings on the page itself:

Decorator example

This is a warning.
This is an error.

In this post I’ve attempted to further demonstrate just how powerful and flexible Angular is for client-side development. I’ve created a fiddle with full source code for you to experiment with on your own. Enjoy!

Thursday, January 9, 2014

Understanding Providers, Services, and Factories in Angular

I’ve read quite a few posts (as well as questions posed) about the differences between services and factories in Angular. I’ve seen just as many attempts to explain it and even fell victim to trying to force an explanation for the difference myself. The answer is more simple than you may think and is evident if you browse the Angular source code and then re-read the documentation. When this clicked for me I had to share it because so many people seem to make more out of it than it is.

The biggest misconception I see is the idea that factories and services have anything to do with being a singleton. The reality is that both methods create singletons (unless you game them to generate new instances).

So here it is. I’m going to summarize then follow up with some examples;
  • Use a service when you want to pass a constructor function. The function will be invoked with the “new” operator and the result stored.
  • Use a factory when you want to return the object from a function (i.e. factory pattern). The function will be called and the result stored.
  • Use a provider when you want to be able to provide module-wide configuration for your object before making it available.
That’s it! It’s real simple. The key to note first is that factories and services end up with the same result, they just use different approaches. With the factory approach you can specify a function to resolve your dependencies and then return an object that uses them, like this:

app.factory('myAlertFactory', ['myAlert', function (myAlert) {
    return {
        alert: function (message) {

Notice that the outer function takes a dependency on a service called “myAlert”. Angular will wire that dependency, call your function and store the result. In this case I pass back an object with an alert method that “passes through” to the alert method on the myAlert service. Essentially I’ve created a “myAlertFactory” object I can use to reference that is a proxy to the underlying “myAlert” object.

The problem with the factory approach is that some languages like TypeScript lean you towards a more class-based approach, and other languages like CoffeeScript enforce it. You can’t just return an arbitrary object from the factory function, so instead you need a way to pass the type onto Angular (remember in JavaScript a custom type is really a constructor function).

This will work fine:

app.service('myAlertService', MyAlertService);

The type is defined like this:

function MyAlertService(myAlert) {
    this.alert = function (message) {
MyAlertService.$inject = ['myAlert'];

Notice that this is a constructor function. It also takes on a dependency, only this time I used a different method to annotate the class so Angular knows what to inject. The end result is exactly the same, so your choice of factory or service should be based on your preference for supplying the instance – do you prefer to create classes and pass the constructor function, or would you rather return something explicitly from a factory function? It’s your choice. The service and factory calls wire up the object and refer to how you prefer to make it, not how the app will consume it.

So what about provider? A provider is a special case that allows for configuration. If you don’t need module-wide configuration, go for a service or factory instead. Think of a provider as sitting on top of a service. The provider is an object that can handle configuration. The first time the service itself is needed, Angular will call the $get function on the provider. This will return an instance that is subsequently tracked like any other item that was wired up using a service or factory.

To illustrate, let’s implement the “myAlert” service that was passed into the two previous examples. The service does what you’d expect – it raises an alert – but it can be configured one time only to prepend a date. It will either use the message, or use the combination of the current date and the message. The provider looks like this:

function MyAlertProvider() {
    var showTime = false;

    this.setShowTime = function (show) {
        showTime = !! show;

    this.$get = ['$window',
    function ($window) {
        return {
            alert: function (message) {
                var dateStamp = new Date();
                if (showTime) {
                    $window.alert(dateStamp.toString() + ": " + message);
                } else {

It contains an internal variable for configuration, exposes a method to configure it, and supplies a $get method to generate the instance (in this case, we’re using the inline annotation to inject the $window service). Note the convention is to take the name you’re going to use for the service and append “Provider” to the end. Here is the set up for the provider. Notice it is named without the provider suffix:

var app = angular.module('myApp', []);
app.provider('myAlert', MyAlertProvider);

And here the module configures it to prepend the date. Notice the dependency requested is for the provider, not the service itself:

app.config(['myAlertProvider', function (myAlertProvider) {

Finally, I can take all of these items and expose them in a controller like this:

app.controller('MyController', [
    '$scope', function (myAlert, myAlertService, myAlertFactory, $scope) {
    $scope.alert = function () {
        myAlert.alert("This is an alert!");
    $scope.alertService = function () {
        myAlertService.alert("This is an alert!");
    $scope.alertFactory = function () {
        myAlertFactory.alert("This is an alert!");

That’s it. The behavior of the alert calls depends on the one-time configuration of the provider. The service and factory proxies are identical despite the different way they were wired up. If I wanted to make the optional date a parameter and not a configuration option, I would do away with the provider and just use a service or a factory. The full working example is available to you at the following link. Try commenting out the .config call to see the default alert without dates added.