Check out our new training course on AngularJS for Flex Developers

The Future of Flex and the Flash Player

This question comes in from a reader, about the future of Adobe Flex and the Flash Player:

Hello Jeffry, I know you because some answers your in StackOverFlow.

But my contact is because in Brazil we company is totally based in Adobe Flex used Flash builder 4.6 and AIR for mobile, and I would know you suggestion about future of Flex and flash.

I believe that programming for long year ahead because all programmer in my company lover Flex but sometime I have fear Adobe finish Flash player and my apps canĀ“t running in my clients.

I wrote a lot about the future of Flex in the past.

But, all those posts are few years old. What do I think today?

First, I am not an Adobe employee and am no longer part of the Adobe Community Professional program. I cannot offer any personal insight into what Adobe may do with the Flash Platform.

I do think the Flash Platform will be around for a long time. However, I do not see Flash as a growth area.

It is very difficult for me to run a Flash Debug Player on my Surface Book

Most new browser based applications are written using HTML5-based technologies. I have had success with AngularJS in the HTML5 world. I even wrote a training course about AngularJS for Flex Developers.

AIR for mobile seems a lot more viable than the browser based Flash Player. I know a lot of gaming companies still use AIR for mobile deployment.

In terms of Flex, the Apache Flex team has done wonderful things with Flex. Since you're still on Adobe Flex; I recommend you consider upgrading to the latest version of Apache Flex.

If your clients do not have problems running your apps today; I'm sure they'll continue to run them throughout the next year without any problems.

For those out there who are considering re-writing your apps to use HTML5 tools; feel free to reach out. I am available for consulting, training, or mentoring.

How do I copy an object in AngularJS?

I was recently working on an AngularJS project for a client. Some data was shown on a screen, and the user would click an edit button to open the same data in a popup modal. The problem I ran into was that any items changed in the popup where automatically changed in the main screen. This was causing some undesirable side affects. What if the user decided to cancel their changes or close the popup? The main screen would be affected.

I Decided to get around this by creating a copy of the object in question. I sent that copy to the popup; then when the popup is closed I can check whether the data was saved and make changes in the main app. But, if the changes in the popup are cancelled, I can dismiss the popup without having to modify the main app.

The question is; how do I perform a deep copy of an object in AngularJS? Use the copy method.

Here is how you can set up an application.

First, import the Angular framework, create a sample module, and a controller:

<script src="//"></script>
angular.module('copyTest').controller('copyController', ['$scope', function($scope){

For this demo, create two separate objects, the baseObject and the objectCopy. The baseObject will contain a mock user object, with an id property, a firstname property, and a last name property:

$scope.baseObject = {
id : 1,
firstName : 'Jeffry',
lastName : 'Houser'

The objectCopy will initialize as an empty object:

$scope.objectCopy = {};

I'll build out a UI For editing object properties; then come back to the script:

<body ng-app="copyTest">
<div ng-controller="copyController">
<h2>Base Object</h2>
ID: <input type="text" ng-model=""> <br/>
First Name: <input type="text" ng-model="baseObject.firstName"><br/>
Last Name: <input type="text" ng-model="baseObject.lastName"><br/>

<h2>Copied Object</h2>
ID: <input type="text" ng-model=""> <br/>
First Name: <input type="text" ng-model="objectCopy.firstName"><br/>
Last Name: <input type="text" ng-model="objectCopy.lastName"><br/>

<button ng-click="onCopy()">Copy Object</button>
<button ng-click="onReset()">Reset Base Object</button>

This app adds the Angular module onto the ngApp tag and the ngController onto a div. The user properties on both the base object and the copied object are put into text inputs. I also add two buttons, one to perform a copy from the base object to the objectCopy; and a second to reset the base object to its default values.

Load the app and you should see something like this:

Now, let's implement the onCopy() and onReset() methods. onReset() sets the baseObject to it's default state:

$scope.onReset = function(){
$scope.baseObject = {
id : 1,
firstName : 'Jeffry',
lastName : 'Houser'

The objectCopy is untouched.

The onCopy() method copies the base object into the objectCopy object and the baseObject is untouched:

$scope.onCopy = function(){
$scope.objectCopy = angular.copy($scope.baseObject);

Load the app and play with the options. This demo shows that edits to one object are not going to have an affect on the other object.

Modify the base object and click the copy button. The objectCopy fields will be populated with data. Change the objectCopy fields and the baseObject fields are not affected. Reset the baseObject and you'll see the objectCopy is not affected.

Play with the code here.

Sign up for DotComIt's Monthly Technical Newsletter

How do I Copy to the Clipboard with AngularJS?

Last week I wrote about using ClipboardJS to copy text the Clipboard using JavaScript. I wanted to extend on that article and show some examples of how to use that library within the context of an AngularJS Application.

ClipboardJS and AngularJS can exist in the same HTML page. This is my preferred approach for using the two together.

First, import the Clipboard and Angular libraries:

<script src="//"></script>
<script src="//"></script>

Next, create an Angular module:


Now the Clipboard library must be initialized. This could be done with any random JavaScript code, but I like to do it in an Angular config block:

angular.module('clipboardTest').config( function(){
new Clipboard('.btn');

Next, create an Angular controller:

angular.module('clipboardTest').controller('clipboardController',['$scope', function($scope){
$scope.someValue = "Some Text";

The controller creates a single value and puts it in the $scope. We'll use the $scope value as the target value for the ClipboardJS library.

Let's put together the UI Behind this app:

<body ng-app="clipboardTest">
<div ng-controller="clipboardController">
<input id="input" value="{{someValue}}">
<button class="btn" data-clipboard-target="#input">Copy</button>
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#input">Cut</button>

The Angular module is put on the body tag with the ngApp attribute. Inside that is a div with the controller. Three elements are inside the angular view. The first is the text input. This uses the Angular binding syntax of double curly brackets to display $scope.someValue from the controller in the view. This input is the target for the clipboard library. The two buttons are identical to what we used in the previous sample.

Running the app, you'll see that the app with Angular works the same as the example from my previous article, without Angular in the mix. The use of Angular is just some syntactical sugar.

Play with the app here.

I'm sure that ClipboardJS could be rewritten as an Angular directive; but it is not required to use the two together.

Sign up for DotComIt's Monthly Technical Newsletter

Using the Surface Book as a Programmer - Four Months In

I am the owner of a Surface Book; Microsoft's premier Windows Laptop/Tablet Hybrid. I've been meaning to write a review about it. As I start this, I'm downloading a new Windows ISO while attempting to apply a fix for corrupt display files and thought I'd take some time to put down my thoughts.

Here is all the good and bad about the Surface Book, according to a programmer who has used it for 4 months.

Getting a Surface Book?

I'm a small business owner and try to replace my main work machine every four years or so. My Thinkpad had started to make a sporadic horrible noise for no discernible reason, so I was in the market for a new laptop. The Surface Book was announced a couple of weeks after this fan noise started. You don't often see windows laptops with the design sense of a Mac. I decided to go all in. I pre-ordered the day after it went on sale, but had numerous pre-order problems, documented elsewhere. Eventually, I got a Surface Book on Friday October 30th. It has been my primary dev machine for about four months at the time of this writing. Here is my attempt at an unboxing video:

Who Am I?

My business cards say "Technical Entrepreneur." I'm a small business owner looking for opportunities to do cool things and share them with others. Primarily I make money building business applications. Someone else makes it pretty, but I make it functional. I've worked with many brilliant designers--but that isn't me. I'm the guy who makes things work.

For daily use; I need a computer that can run multiple development programs. In any given day, I'll use IntelliJ, Eclipse, NodeJS, ColdFusion, PHP, Apache, Java, Flash, Remote Desktop, SQL Server, MySQL and multiple browsers with dozens of active tabs.

I am a writer, and occasional screencaster. I write one technical blog post a week. I created a training course on AngularJS for Flex Developers, which includes over four hours of screencasts on AngularJS. I write game reviews for Having a laptop that can play computer games is a nicety especially if I'm on the road for a client and need to pass the time in a hotel or while in transit.

The bulk of my work is done out of a home office, so on normal days I have my Surface Book docked, with an external keyboard, mouse, and monitor. The reason for having a laptop is because it is great to have my work with me when I am meeting with clients.

So, as a quick summary. I need a laptop for:

  • Programming
  • Writing
  • Screen Recording
  • Moderate Gaming

I was pretty sure the Surface Book would fit the bill, plus had some cool factor related due to the hybrid nature. I decided to go for it. How did it do? Read on!

First Impressions

There is a lot to love about the Surface Book. The construction is solid in my hand. The trackpad is responsive and easy to use. The keys are light to the touch. I have no problem typing in the keyboard, despite using an external mechanical keyboard at my desk.

The screen is the highlight of the machine. Words cannot express how beautiful this screen is. I was worried that the extra-large resolution on a relatively tiny display would make most programs unusable; but that is not the case. Many install programs, such as the ColdFusion server, were difficult to read; but once the install completed, the programs run smoothly.

The bulk of the internals are in the Clipboard section. Usually the screen is the lightest part of the laptop, but here it is the heaviest. I've heard some worries that this weight distribution will cause issues when using the unit on your lap. I adjusted to this very quickly. Microsoft created a dynamic fulcrum hinge to support the heavy Clipboard. The hinge does its job well and the unit is perfectly serviceable in your lap. The Clipboard on its own is surprising light. It surprises people when they feel it. It looks too big to be this light.

The hinge doesn't allow the clipboard part of the machine to lay flat against the keyboard, leaving a gap when the Surface Book is closed. Some have worried that items would get stuck inside the Surface Book while it was in their bag. I have not had that issue. I use a laptop backpack with a special laptop compartment, which protects the unit from interacting with other loose items.

The machine loads faster than any Windows machine I've ever used. Boot times are iPad-like. Surface Books use two different brands of hard drives, a Samsung or Toshiba. I got the Samsung, which is the slower drive. Hard drive access is just one aspect of overall speed; and I suspect you'd be hard pressed to notice slow-downs even if you were comparing two machines side by side. The Internet led me to believe that the 128GB machines will have the biggest performance differences in hard drive performance. The 512GB version is plenty fast for my purposes.

The battery life is great. I can spend a day with clients in New York City and do not have to plug the laptop in at all. The commute is three hours one way, so this is a 12-hour day minimum. I get home with battery life to spare. Like many new devices today, the battery for the Surface Book is not removable. I have some fear this may cause long term issues. With past laptops I've lengthened the life of the machine by replacing the battery.

The Surface Book's screen resolution is 3000 by 2000, which is pretty high for a 13 inch screen. The bulk of software I run is DPI aware and adjusts itself accordingly. Programs even adjust when moving between the Surface Book's High DPI screen to a 'normal DPI' external monitor. Some programs, such as Eclipse, needed to be told to run in the High DPI resolution mode. Otherwise everything looks too small. I use this approach to tell programs to ignore the high DPI. You can also set this in the compatibility settings for the program's executable.

Before we move on, here is a vid I created of detaching and re-attaching the Clipboard:

Programming on the Surface Book

My Surface Book has 16GB of RAM and it has no problem running all the software I need for programming. Right now, I have IntelliJ, Chrome, Firefox, Edge, Apache, SmartGit, and ColdFusion running in the background. Not to mention Word and Notepad. The machine handles all of this--and often more--like a champ.

Keyboard Remapping

When coding I use the right control key and the right and left arrow key to move between words. This is a quick navigation through lines of code, often moving forward or back to change or copy a variable name. Unfortunately, the Surface Book keyboard does not have a right control key:

After some struggling, I decided to use a keyboard remapper to remap the 'context menu' key to act as a right control. SharpKeys from CodePlex, made this very easy. I think under the hood it makes a registry change. This makes my life a bit easier and I don't have to relearn years of muscle memory training.

Flash Development

I come from a background as a Flex Developer. Flex is a programmer's way to make Flash movies and for a while it was a very successful way to create business applications. New Flex development is rare now, but I still handle maintenance requests from clients; both old and new. Arguably I'm one of the world's most prominent Flex developers, so I don't often turn down the work. Flash development is a problem on the Surface Book because there is limited support for the Flash Debug player. Let's look at the browsers:

  • Edge comes with a built in Flash Player and there is no way to replace it with a Flash Debug Player. (Source 1 and Source 2)
  • Internet Explorer 11 comes with a built in Flash Player and there is no way to replace it with a Flash Debug Player. (Same Source as Above)
  • Chrome does support a Flash Debug player, but it is tough to install. To use the Flash Debug player you must launch Chrome with the -disable-bundled-ppapi-flash flag. I'm not sure if that is possible when launching from Eclipse/Flash Builder and haven't gotten around to trying it.
  • Firefox does support the Flash Player debug version. However, there is an error with Flash inside Chrome on High DPI Screens. You can disable the display scaling for Firefox, as mentioned previously; but this solution only worked for Browser Flash is I had an external monitor plugged in.

So, Flash Development is tough and has prevented me from taking the old laptop off my desk.

Writing on the Surface Book

The Surface Book would be great for writers. It runs Word wonderfully. My blogging software is browser based, and there are no issues accessing it on the Surface Book.

Writing with the Pen

I'm routinely in New York City to visit clients. On the way home, I'll take out the Clipboard, Pen, and use OneNote to brainstorm song lyrics for my music-related hobby. It works astoundingly well.

One of my desired use cases for the Surface Book was to use it take notes at client meetings. Automatically digitizing the notes and syncing them to my phone would be a great time saver. Unfortunately, when in meetings with clients I often need to share my screen to load a web site or presentation or other information. During such time it is not practical to share the screen I am using to take notes on. I never use the Surface Book for this use case. Instead of carrying around a second laptop for sharing, I now stick with the paper notepad and pen for my meeting notes.

Drawing with the Pen

Since I'm on the topic, I think the Surface Book pen and touch screen would be great for artists. I find the pen very responsive both when writing and when drawing. This is something I drew with Freshpaint as an experiment:

This is about as good as I'm able to draw. I'm sure a trained designers or artists would do much better.

Gaming on the Surface Book

I've had mixed experiences with gaming on the Surface Book. I downloaded Minesweeper, Solitaire, and a Sudoku game from the Windows App store. They all work great. The Firefox Flash bug prevents me from playing my casual game addiction, Bloon Monkey City. The game screen is too small. Other browsers I've tried zoom differently than Firefox does; so that makes the game too large.

Games I review for JustAdventure are primarily point and click adventure games. Most of them are not taxing to recent computers. To date, I've only tried to install one point and click adventure game, the Book of Unwritten Tales: Critter Chronicles. It gives an error about a dll missing from the computer. I was able to find some documentation on this error, but none of the fixes worked. I eventually gave up and moved back to my main desktop for gaming.

I know based on Surface forums a lot of people are having great success gaming on the Surface Book. I think my experience is too limited to draw any long-term conclusions. This was never my prime use case.

What is wrong with the Surface Book?

I have a list of problems I've had with the Surface Book and I've kept notes. Many of the issues have gone away with updates. Some problems are brand new, thanks to those same updates. I've separated this list into current problems and sporadic / fixed problems.

Sporadic and One-Time Issues

Here are some issues that have only happened once or twice then went away never to return:

  • Display Driver Crashes: Display driver crashes were common in the first few weeks of using the machine. A message showed up in the bottom right corner about it. These errors went away and I haven't seen it in months. This is the type of error I liked because the display driver would reset itself w/o a machine reboot or any other input from me. I just had to deal with a notification that went away on its own.
  • No Trackpad: Sometimes the machine's track pad wouldn't work. This was sporadic and may have had something to do with waking up from sleep mode, but I'm not sure. A reboot fixed the error every time.
  • Blue Screens: On my first full day using the computer as my primary dev machine; I saw two blue screen crashes. They were common in the early days, but I haven't seen one in months.
  • Battery Power when plugged in: When disconnecting Clipboard and plugging it back in; the Surface uses battery power instead of the dock power. The solution is unplug the dock and plug it back in. I saw this error twice, then had an update and it went away, I hope forever.
  • Master Volume Doesn't Work: The master volume stopped working for about a week during Christmas vacation. The volume up button appeared to bring up the control-alt-delete screen. I could control the volume of individual programs in the volume control panel, but nothing would make the master volume work. I contacted support via chat. They eventually called, and then hung up on me. I brought the unit into a Microsoft Store where the problem went away when I booted the machine. They had no insight; and the problem never came back.
  • No Internet: In the middle of February, I lost all Internet access. No wifi and no wired connection through the dock. I could access file shares on the network, and could ping IP address but I appeared to have no DNS lookups. It was bizarre. I found a solution here. Basically, I had to deactivate IP6 in Network adapter settings; reboot the machine, then reactivate IP6. I spent a half day on this.
  • A Blank Surface Book Screen: The day I was writing this article, my Surface Book screen went blank. I had left the computer for a bit and came back to find the issue. Thankfully, this is a known issue, and the fix is to press the windows key + control + shift + B at the same time. I understand this is a hotkey for resetting the display driver. I've only had this scenario happen twice; but I've seen a lot of complaints about it.

Open Issues

Here are some open issues with my Surface Book setup:

  • Random Crashes or Reboots: Sometimes I leave my computer on when I go out to lunch. When I come back and sign in, it is as if the computer is being booted up for the first time today. None of the programs I left running are running. I have no explanation for why this happens. It is sporadic.
  • No External Monitor: When I come back to my desk after lunch, nothing will display on my external monitor. The computer seems to think the monitor is there; but the monitor is blank. Trying to disable the monitor, or re-enable it in display settings gives an error. This started after the last Windows update. I found a solution, but it is tedious.

    1. First unplugged the external monitor from the dock.
    2. Then unplug the dock from the computer.
    3. Then plug the external monitor into the Surface Book. This resets and the secondary monitor displays properly.
    4. Now unplug the secondary monitor from the computer and plug it into the dock
    5. Finally, reconnect the dock to the computer.

    Just like magic you'll have a working external monitor again. I wish the Windows Key + Control + Shift + B command worked here, but it doesn't.

  • Clipboard Detached when it isn't: The Surface Book perpetually thinks the Clipboard is not attached even when it is. This error started after the last firmware update. Sometimes a reboot will help. Sometimes a reboot into the EUFI screen will help. Do this by pressing the volume up button at the Surface while the Surface Logo appears on the screen. After that simply exit the EUFI screen. Neither of these fixes are consistent. Sometimes they don't work. Sometimes the problem comes back.

One More Thing

I have no idea how this dent happened:

So, if you get one, be careful. The unit is not indestructible.

Final Thoughts

The Surface Book is an awesome, if imperfect, machine. I'm frustrated as I write this because I have more issues today than I did three weeks ago. The last two updates were not kind to me. Based on Reddit forums, people have had issues lots more serious than I. In retrospect, I could survive without the clipboard functionality; but it is a nice to have. I expect all my issues are software related and will be fixed with firmware or software updates. I bet in another six months; the Surface Book will be the perfect computer.

This whole blog post, including video and photo editing was done on the Surface Book!

How do I Copy to the Clipboard with JavaScript?

Copying something to the clipboard is one area where ActionScript has traditionally been superior to JavaScript and HTML. For the longest time there was no way to easily copy something to the clipboard from JavaScript and have it work in all browsers. Even sites like Github have traditionally relied on a hidden swf in the background to copy their repo URLs into the clipboard. As browsers, progress, this starts to change. I found a great JavaScript library, clipboardjs that gives us copy to clipboard functionality without the use of Flash.

Using ClipboardJS to Copy

The first step in using the library is to import the library:

<script src=""></script>

Once the library is imported, we must initialize it:

new Clipboard('.btn');

The initialization process uses JavaScript's new keyword to create an instance of the Clipboard object. The argument refers to the item in which the Clipboard library will listen for copy events. In this, case we are telling the library to look for all page elements where the class was named 'btn'. On said elements, the library will look for special attributes that tell the library how to operate.

First, we need an input that can be copied:

<input id="input" value="Some Text">

This input contains the target text that we want to copy.

Next, we need a button to perform the copy:

<button class="btn" data-clipboard-target="#input">Copy</button>

This button uses the class btn; which is the name of the class we used when initializing the Clipboard object. The clipboard object looks for the data-clipboard-target attribute; and uses that value to find the target text to copy.

That is all we need to copy the text; the library takes care of the rest.

Test this out.

Using ClipboardJS to Cut

ClipboardJS can also be used for performing cut operations. You just need to add one additional data attribute to the trigger element:

<button class="btn" data-clipboard-action="cut" data-clipboard-target="#input">Cut</button>

The data-clipboard-action is specified. The default is copy, however in this case we set it to cut. The text in the input will copy it into the clipboard and remove it from the relevant input.

Test this out.

Sign up for DotComIt's Monthly Technical Newsletter

How do I remove a property from an object in JavaScript?

Programmers specialize their knowledge. They learn some things extremely well, but often have limited experience beyond that. It makes sense, because you learn enough to solve the problem at hand then stop looking for an answer.

I'm no different! Even some languages, like JavaScript have aspects I never learned. This post is about one of those aspects.

I was working on on an Angular app for a client and added a 'reset' function to many of our shared data models. When the user logged out, we wanted to make sure that no data was in memory from that user's session. My initial approach was to reset all the values back to a defaults value. Arrays went back to empty arrays; numbers went to 0 or -1; a strings went back to empty strings. One of my colleagues suggested that instead of defaulting the values; we could delete them from the service object.

"Huh, I said? How do you do that?"

Use the delete operator.

How do use the Delete Operator

The delete operator will remove a property from an object. I put together a simple sample to demonstrate this.

First, create an object:

myObject = {
value1 : 'Foo',
value2 : 'Bar'

This snippet creates an object named myObject with two properties on it.

Next output the object, so you can see what it is:


Then run the delete command to remove one of the object's properties:

delete myObject.value1;

The delete command starts with the delete operator, followed by a space. After that specify the object and property where you want items to be removed. Object property notation is used; so a dot separates the object variable and its property.

Next, output the object again:


Int he two logs you'll see that the value1 property is part of the object in the first log; and removed from second log.

I'm amazed I've never run into that operator before.

Play with a sample here.

Sign up for DotComIt's Monthly Technical Newsletter

Using Angular to Open a Link in a New Window with a Button click

I was recently working on a client app and had to open a link in a new window. This is easy to do with an anchor, because you can specify the target. When you're dealing with a HTML button that answer was not as obvious.

How does one use Angular to open a link in a new window on a button click? The answer is to use the JavaScript open method and Angular's $window service.

Let's create a sample app. First, load in the Angular framework:

<script src="//"></script>

Then create an Angular Module:


Next, create an Angular controller:


Angular injects two services into the controller for this sample: the $scope service and the $window service. The $scope service is used to share data between the view and the controller. The $window service is an Angular service representing a reference to the current window object.

Now create an open window function:

$scope.openWindow = function(){

We can call the open() function directly on the angular $window service and it will do what we want.

Next we need a button that will trigger this function:

<body ng-app="openWindowTest">
<div ng-controller="controller1">
<button ng-click="openWindow()">Open Window</button>

The Angular module is attached to the body tag using the ngApp directive. The controller is attached to the div using the ngController directive. The button uses the ngClick directive to call the open window method.

Try it, and you'll see my blog opens in a new window, or tab, depending on your browser. This is one of the simpler JavaScript tasks I've had to tackle this week.

Sign up for DotComIt's Monthly Technical Newsletter

How can I avoid Cross Domain Restrictions When doing HTML5 Development?

Sometimes when I'm developing an HTML5 app for a client it does not make sense to set up the client's full environment on my local machine.

Sometimes the setup is complicated and the budget doesn't allow me to spend a day or two for setup. Sometimes the apps are leveraging services that spread between multiple departments and servers and it is not practical to set them all up locally. Other times, the client wants me up and running in the shortest order possible. In such situations, I still write code on my local local machine, but access their services remotely.

HTML applications that run in a browser this can cause a problem. The HTML app can't use xmlHTTPRequest to make calls to remote servers. This is done to prevent normal users from running into cross site scripting which are often used for nefarious means.

When developing code locally, however, my use is legit and I need a temporary work around. In these situations, I often go to a a Chrome command line argument that disables cross site scripting restrictions:

pathtoChromeInstall\Chrome.exe -disable-web-security

Once this is in place, I am able to run HTML code on my local server that can make remote service calls to my client's server. Then all is good in the world and I'm able to continue to work productively with my client.

There is a great StackOverflow writeup on this point.

Comparing AngularJS Providers, Factories, Services, Constants, Values, and Decorators

This post is is designed as a reference cheat sheet. I've written about Providers, Factories, Services, Constants, Values, and Decorators in more detail in past posts. This is a simple table intended to compare them. I had something similar in the bonus materials of my AngularJS training course; but it didn't include Constants, Values, or Decorators.

Element Singleton Instantiable Configurable Comment
Provider Yes Yes Yes
  • A Configurable Factory.
  • The code behind both the Service, Factory, Value, Constant, and Decorator.
  • Available during the configuration phase.
  • Can be intercepted by decorator.
Factory Yes Yes No
  • A Injectable function.
  • Returns an Object
  • Easy to pass arguments to a constructor since you create your own object.
  • Can be intercepted by decorator.
Service Yes No No
  • A Simple Injectable Constructor.
  • Uses the new keyword to create an object.
  • Returns an instance of the object.
  • Can be intercepted by decorator.
Value Yes No No
  • A Simple injectible value.
  • Can not be injected into config blocks.
  • Can be intercepted by decorator.
Constant Yes No No
  • Cannot be intercepted by a decorator.
  • It is possible to change this value programmatically.
Decorator Yes No No
  • Used to modify other elements in this list, except constants.
  • Can be intercepted by another decorator.

Sign up for DotComIt's Monthly Technical Newsletter

Using Decorators in AngularJS

A decorator is a design pattern. A decorator is, basically, a wrapper for an object. It doesn't change the API of that object, but does change the functionality.

One use for decorators might be to add authentication code to a services API. The authentication code could be encapsulated and use for all service calls; but doesn't inherently change the functionality of a single method. Decorators can be used for caching purposes in a similar manner.

There is a decorator method implemented as part of the AngularJS library. It allows you to use a decorator to modify an Angular service, factory, provider, or value. This feature was added in Angular 1.4, before I wrote my AngularJS training course. This article will tell you how to use a decorator in the context of an AngularJS Application.

Creating a Simple Angular Application

The first step in any AngularJS application is to import the angular framework:

<script src="//"></script>

Then, create a module:


The module should be put in a script block, in case that wasn't obvious.

Next, create a service:

angular.module('decoratorTest').service('myService', function(){
return {
value : "Value in Service"

The service is named myService; and the service object contains a single property, named value.

Next, create a controller. The controller will add the myService to the $scope so the value can be displayed within a view:

$scope.myService = myService;

The controller's name is controller1. It has two services injected into it: Angular's $scope service and our custom myService. Create a view to output the data:

<body ng-app="decoratorTest">
<div ng-controller="controller1">
<b>Service in Controller 1</b>: {{myService.value}}

The decoratorTest module is added to the body tag using the ngApp directive. The controller1 controller is put on a div with the ngController tag. The service value is output. You should see something like this:

This a simple app that simply displays some data from the controller in the view. It does not yet use a decorator.

Using a Decorator

Now let's add a decorator to the app. This decorator will change the value constant instead the service. AngularJS defines a decorator using a method off the main module. This is the generic format:

AngularJSModule.decorator(ServiceTobeModified, ['$delegate',function($delegate){
return {
// modified service

The decorator function is called on the module. It accepts two arguments. The first argument is a string that refers to the service, or factory, or provider, or value to be modified. The second argument is the modifier function. In this case, we are injecting a single item into the decorator and that is the service function to be modified. The $delegate argument is injected to the decorator function using standard AngularJS dependency injection syntax. It represents the service as is, without any modifications.

For the purposes of this sample, we are going to modify the value on the service to say 'decorated' after the original value. This would be our modified code:

angular.module('decoratorTest').decorator('myService',['$delegate', function($delegate){
return {
value : $delegate.value + " decorated"

Run your updated app and you should see something like this:

Play with the code

Final Thoughts

Technically we could create decorator like functionality using providers and an Angular config. But, using the decorator function is a much easier approach. It also allows us to add decorators to our app at any point, not just at the config stage. Decorators can be used for much more advanced purposes than this sample. We could add new functionality or values to our service.

I find decorators are most useful when dealing with third party services that I want to use almost as is, but make minimal changes. Have you been using them? What for?

Sign up for DotComIt's Monthly Technical Newsletter

More Entries

All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version