About the Author:

History and Background of JavaScript Module Loaders

June 13th, 2016

Application logic for web apps continues to move from the back end to the browser. But as rich client-side JavaScript apps get larger, they encounter challenges similar to those that old-school apps have faced for years: sharing code for reuse, while keeping the architecture separated into concerns, and flexible enough to be easily extended.
One solution to these challenges has been the development of JavaScript modules and module loader systems. This post will focus on comparing and contrasting the JavaScript module loading systems of the last 5-10 years.
It’s a comprehensive subject, since it spans the intersection between development and deployment. Here’s how we’ll cover it:

  1. A description of the problems that prompted module loader development
  2. A quick recap on module definition formats
  3. JavaScript module loader roundup – compare and contrast
    1. Tiny Loaders (curl, LABjs, almond)
    2. RequireJS
    3. Browserify
    4. Webpack
    5. SystemJS
  4. Conclusion

The problems

If you only have a few JavaScript modules, simply loading them via <script> tags in the page can be an excellent solution.

<head>
 <title>Wagon</title>
 <!-- cart requires axle -->
 <script src=“connectors/axle.js”></script>
 <script src=“frames/cart.js”></script>
 <!-- wagon-wheel depends on abstract-rolling-thing -->
 <script src=“rolling-things/abstract-rolling-thing.js”></script>
 <script src=“rolling-things/wheels/wagon-wheel.js”></script>
 <!-- our-wagon-init hooks up completed wheels to axle -->
 <script src=“vehicles/wagon/our-wagon-init.js”></script>
</head>

However, <script> establishes a new http connection, and for small files – which is a goal of modularity – the time to set up the connection can take significantly longer than transferring the data. While the scripts are downloading, no content can be changed on the page (sometimes leading to the Flash Of Unstyled Content).  Oh yeah, and until IE8/FF3 browsers had an arbitrary limit of 2 simultaneous downloads because bad people back in the day were bad.
The problem of download time can largely be solved by concatenating a group of simple modules into a single file, and minifying (aka uglifying) it.

<head>
<title>Wagon</title>
<script src=“build/wagon-bundle.js”></script>
</head>

The performance comes at the expense of flexibility though. If your modules have inter-dependency, this lack of flexibility may be a showstopper. Imagine you add a new vehicle type:

<head>
<title>Skateboard</title>
<script src=“connectors/axle.js”></script>
<script src=“frames/board.js”></script>
<!-- skateboard-wheel and ball-bearing both depend on abstract-rolling-thing -->
<script src=“rolling-things/abstract-rolling-thing.js”></script>
<script src=“rolling-things/wheels/skateboard-wheel.js”></script>
<!-- but if skateboard-wheel also depends on ball-bearing -->
<!-- then having this script tag here could cause a problem -->
<script src=“rolling-things/ball-bearing.js”></script>
<!-- connect wheels to axle and axle to frame -->
<script src=“vehicles/skateboard/our-sk8bd-init.js”></script>
</head>

Depending on the design of the initialization function in skateboard-wheel.js, this code could fail because the script tag for ball-bearing wasn’t listed between abstract-wheel and skateboard-wheel. So managing script ordering for mid-size projects got tedious, and in a large enough project (50+ files), it became possible to have a dependency relationship for which there wasn’t any possible order that would satisfy all the dependencies.

Modular programming

Modular programming, which we explored in a previous post, satisfies those management requirements nicely. Don’t head out to celebrate just yet though – while we have a beautifully organized and decoupled codebase, we still have to deliver it to the user.
The stateless and asynchronous environment of the web favors user experience over programmer convenience. For example, users like it when they can start reading a web page before all of its images have finished downloading. But bootstrapping a modular program can’t be so tolerant: a module’s dependencies must be available before it can load. Since http won’t guarantee how long that fetch will take, waiting for dependencies to become available gets tricky.

Javascript Module formats, and their loaders

The Asynchronous Module Definition (AMD) API arrived to solve the asynchronous problem. AMD takes advantage of the fact Javascript is processed in two phases: parsing (interpretation), when the code is checked for syntax, and execution, when the interpreted code is run.

At syntax time, dependencies are simply declared in an array of strings. The module loader checks if it has that dependency loaded already, and performs a fetch if not. Only once all the dependencies are available (recursively including all dependencies’ dependencies) does the loader execute the function portion of the payload, passing the now-initialized dependency objects as arguments to the payload function.

// myAMDModule.js
define([‘myDependencyStringName’, ‘jQuery’], function (myDepObj, $) { ...module code...

This technique solved the file ordering problem. You could again bundle all your module files into one big fella – in any order – and the loader would sort them all out. But it presented other advantages too: there suddenly became a network effect to using publicly hosted versions of common libraries like jQuery and Bootstrap. For example, if the user already had Google’s CDN version of jQuery on their machine, then the loader wouldn’t have to fetch it at all.
Ultimately, AMD’s ‘killer app’ wasn’t even a production feature. The best and least expected advantage of using a module loader came from referencing individual module files during development, and then seamlessly transitioning to a single, concatenated and minified file in production.
On the server side, http fetches are rare, as most files already exist on the local machine. The CommonJS format uses this assumption to drive an synchronous model. The CJS-compatible loader will make available a function named require(), which can be called from within any ordinary Javascript to load a module.

// myCommonJSModule.js
var myDepObj = require(‘myDependencyStringName’);
var $ = require(‘jQuery’);
if ($.version <= 1.6) alert(‘old JQ!’);

CJS eliminates the cumbersome boilerplate syntax of AMD’s define() signature. Back-end pros who use languages like Python often find CJS a more familiar pattern than AMD. CJS can also be statically analyzed more easily – for instance, in the example above, an analyzer could infer that the object being returned from require(‘jQuery’) should have a property named ‘version’. IDEs can use this analysis for useful features like refactoring and autocomplete.
Since require() is a blocking function, it causes the Javascript interpreter to pause the current code and switch execution context to require’s target. In the example above, the console log won’t execute until the code from myDependencyStringName.js has loaded and finished.
In the browser, downloading each dependency serially as the file is processed would result in even a small app having unacceptable load times. This doesn’t mean no one can use CJS in the browser though. The trick comes from doing recursive analysis during build time – when the file has to get minified and concatenated anyway, the analyzer can traverse the Abstract Syntax Tree for all the dependencies and ensure everything gets bundled in the final file.
Finally, ES6, the most significant update to Javascript in many years, added built in support in the form of the new ‘module’ keyword. ES6 modules incorporate many of the lessons learned from both AMD and CJS, but resemble CJS more strongly, especially in regards to loading.

Reasons not to use a module loader

These days, modular programming and module loaders have become synonymous with rich web apps. But using modular programming does not necessarily require using a module loader. In my experience, only the issue of complicated module interdependence qualifies as absolutely requiring a module loader, but many projects have complicated loading infrastructure they just don’t need.
Adding any technology to your stack has a cost: it increases both the number of things that can possibly go wrong and that you need to understand. Many of the benefits of loaders are just that – benefits – and not requirements. Beware the benefits that sound like no-brainers – You Ain’t Gonna Need It, as it’s a subtle form of premature optimization.
Try running your project without a loader at first. You’ll have greater control over and insight into your code. If find you never need one, you’re ahead, and adding one later is not hard.
The same YAGNI logic applies to the features of whatever module loader you choose. I’ve seen many projects use AMD named modules for no benefit whatsoever (and there’s a substantial cost to it as well). KISS.

Tiny loaders

Early on, as AMD emerged as a leading client-side format, the module loading ecosystem exploded to support it. Libraries from this explosion include LAB.js, curljs, and Almond. Each had a different approach, but much in common: they were tiny (1-4kb), and followed the Unix philosophy of doing one thing and doing it well.

The thing they did was to load files, in order, and afterwards call back a provided function.  Here’s an example from the LABjs github:

<script src="LAB.js"></script>
<script>
$LAB
.script("https://remote.tld/jquery.js").wait()
.script("/local/plugin1.jquery.js")
.script("/local/plugin2.jquery.js").wait()
.script("/local/init.js").wait(function(){
initMyPage();
});
</script>

In this example, LAB starts fetching jQuery, waiting until it finishes executing to load plugin1 and plugin2, and waiting until those are finished before loading init.js. Finally, when init.js finishes, the callback function invokes initMyPage.
All these loaders use the same technical mechanism to fetch content: they write a <script> tag into the page’s DOM with the src attribute filled in dynamically. When the script fires an onReadyStateChange event, the loader knows the content is ready to execute.
LAB and curl aren’t actively maintained anymore, but they were so simple they probably still work in today’s browsers. Almond still gets maintained as the minimalistic version of Require.

RequireJS

Require appeared in 2009, a latecomer among the tiny loaders, but went on to gain the greatest traction due to its advanced features.

At its core, Require is not fundamentally different than the tiny loaders. It writes script tags to the DOM, listens for the finishing event, and then recursively loads dependencies from the result. What made Require different was its extensive – some might say baffling – set of configuration options and operating sugar. For example, there are two documented ways to kick off the loading process: either pointing an attribute named data-main of the script tag that loads RequireJS at an init file…

<script src=“tools/require.js” data-main=“myAppInit.js” ></script>
...or invoking a function named require() in an inline script...
<script src=“tools/require.js”></script>
<script>
require([‘myAppInit’, ‘libs/jQuery’], function (myApp, $) { ...
</script>

…but the documentation recommends not using both, without giving a reason. Later, it’s revealed the reason is neither data-main nor require() guarantee that require.config will have finished before they execute. At this point, inline require calls are further recommended to be nested inside a configuration call:

<script src=“tools/require.js”></script>
<script>
require(['scripts/config'], function() {
require([‘myAppInit’, ‘libs/jQuery’], function (myApp, $) { ...
});
</script>

Require is a swiss army knife of configuration options, but an air of automagical uncertainty hangs over the multitude of ways in which they affect each other. For example, if the baseUrl config option is set, it provides a prefix for the location to search for files. This is sensible, but if no baseUrl is specified, then the default value will be the location of the HTML page that loads require.js – unless you used data-main, in which case that path becomes baseUrl! Maps, shims, paths, and path fallback configs provide more opportunities to solve complex problems while simultaneously introducing unrelated ones.
Worth mentioning is possibly the most “gotcha” of its conventions, the concept of “module ID”. Following a Node convention, Require expects you to leave the ‘.js’ extension off the dependency declaration. If Require sees a module ID that ends in ‘.js’, or starts with a slash or an http protocol, it switches out of module ID mode and treats the string value as a literal path.
If we changed our example above like so:

require([‘myAppInit.js’, ‘libs/jQuery’], function (myApp, $) { ...

Require is almost certain to fail to find myAppInit, unless it happens to be in the directory the baseUrl/data-main algorithm returns. As close to muscle memory as typing the ‘.js’ extension is, this error can be annoying until you get in the habit of avoiding it.
Despite all its idiosyncrasy, the power and flexibility of Require won it wide support, and it’s still one of the most popular loaders on the front end today.

Browserify

Browserify set out to allow use of CommonJS formatted modules in the browser. Consequently, Browserify isn’t as much a module loader as a module bundler: Browserify is entirely a build-time tool, producing a bundle of code which can then be loaded client-side.
Start with a build machine that has node & npm installed, and get the package:
npm install -g –save-dev browserify
Write your modules in CommonJS format, and when happy, issue the command to bundle:
browserify entry-point.js -o bundle-name.js
Browserify recursively finds all dependencies of entry-point and assembles them into a single file:
<script src=”bundle-name.js”></script>
Adapted from server-side patterns, Browserify does demand some changes in approach. With AMD, you might minify and concat “core” code, and then allow optional modules to be loaded a la carte. With Browserify, all modules have to be bundled; but specifying an entry point allows bundles to be organized based on related chunks of functionality, which makes sense both for bandwidth concerns and modular programming.
Launched in 2011, Browserify is going strong.

Webpack

Webpack follows Browserify’s lead as a module bundler, but adds enough functionality to replace your build system. Expanding beyond CJS, Webpack supports not only AMD and ES6 formats, but non-script assets such as stylesheets and HTML templates.
Webpack runs on a concept called ‘loaders’, which are plugins registered to handle a file type. For example, a loader can handle ES6 transpilation (Webpack 2.0 handles ES6 natively), or SCSS compilation.
Loaders feed data into a “chunk”, which starts from an entry point – conceptually similar to a Browserify bundle. Once Webpack is set up, chunks are regenerated automatically as assets  change. This can be very powerful, as you don’t have to remember to edit chunks.
The feature that has everybody really excited is hot module replacement. Once Webpack is in charge of your chunks, while running webpack-dev-server, it knows enough to modify code in the browser as you change the source. While similar to other source watchers, webpack-dev-server doesn’t require a browser reload, so it falls into the category of productivity tools that shave milliseconds off your dev process.
Basic usage is beyond simple. Install Webpack like Browserify:
npm install -g –save-dev webpack
And pass the command an entry point and an output file:
webpack ./entry-point.js bundle-name.js
If you’re limiting use to Webpack’s impressive set of defaults, that command power always comes at a cost though. On one project, our team had several difficult problems – transpiled ES6 didn’t work after Webpack chunked it, and then SCSS worked locally but failed to compile in the cloud. In addition, Webpack’s loader plugin syntax overloads the argument to require(), so it won’t work outside of Webpack without modification (meaning you won’t be able to share code between client and server side).
Webpack has its sights set on the being next-generation compiler for the web, but maybe wait for the next version.

Screen Shot 2016-06-13 at 12.27.23 PM

Google Trends’ Take

Source

SystemJS

Wikipedia defines a polyfill as “additional code which provides facilities that are not built into a web browser”, but the ES6 Module Loader Polyfill which SystemJS extends goes beyond the browser. An excellent example of how agnostic modern Javascript has become about the environment it runs in,  the ES6 Module Loader Polyfill can also be used via npm in a Node environment.

SystemJS can be thought of as the browser interface to the ES6 Module Loader Polyfill. Its implementation is similar to RequireJS: include SystemJS on the page via a script tag, set options on a configuration object, and then call System.import() to load modules:

<script src="system.js"></script>
<script>
// set our baseURL reference path
System.config({
baseURL: '/app'
});
// loads /app/main.js
System.import('main.js');
</script>

SystemJS is the recommended loader of Angular 2, so it already has community support. Like Webpack, it supports non-JS file types with loader plugins. Like Require, SystemJS also ships with a  simple tool, systemjs-builder, for bundling and optimizing your files.
However, the most powerful component associated with SystemJS is JSPM, or JavaScript Package Manager. Built on top of the ES6 Module Loader Polyfill, and npm, the Node package manager, JSPM promises to make isomorphic Javascript a reality. A full description of JSPM is beyond the scope of this article, but there’s great documentation at jspm.io, and many how-to articles available.
Comparison Table

Loader CategoryLocal module formatServer filesServer module formatLoader code
Tiny loadersVanilla JSSame structure as local filesSame format as local filescurl(entryPoint.js’)
RequireJSAMDConcatenated and minifiedAMDrequirejs(‘entryPoint.js’, function (eP) {
// startup code
});
BrowserifyCommonJSConcatenated and minifiedCommonJS
inside AMD
wrapper
<script src=”browserifyBundle.js”>
</script>
WebpackAMD and/or CommonJs (mixed OK)“Chunked” – Concat and minify into feature groupsWebpack proprietary wrapper<script src=”webpackChunk.js”>
</script>
SystemJSVanilla, AMD, CommonJS, or ES6same as localSystemJS proprietary wrapperSystem.import(‘entryPoint.js’)
.then(function (eP) {
// startup code
});

Conclusion

Today’s plethora of module loaders constitutes an embarrassment of riches compared to just a few years ago. Hopefully this post helped you understand why module loaders exists and how the major ones differ.
When choosing a module loader for your next project, be careful of falling prey to analysis paralysis. Try the simplest possible solution first: there’s nothing wrong with skipping a loader entirely and sticking with plain old script tags. If you really do need a loader, RequireJS+Almond is a solid, performant, well supported choice. Browersify leads if you need CommonJS support. Only upgrade to a bleeding edge entry like SystemJS or Webpack if there’s a problem you absolutely can’t solve with one of the others. The documentation for these bleeding-edge systems is arguably still lacking. So use all the time you save by using a loader appropriate to your needs to deliver some cool features instead.

About the Author:

Ng-if Examples, Use Cases, and Caveats

May 12th, 2016

Ng-if is a built-in Angular directive for adding and removing content from the DOM. Ng-if is extremely handy for showing and hiding buttons, links, text, images, or other types of content on a page. We covered the differences between ng-show, ng-hide, and ng-if here, so this post will focus specifically on ng-if syntax, examples, and use cases.

Explore Angular Courses

Why Use Ng-If at all?

Why should we add/remove content from the DOM vs. just hiding/showing it? Why use ng-if at all? It comes down to the way Angular watches for changes in an app. Angular uses a digest loop to watch for changes in an app to make changes in the view or model (two-way data binding). Watches are expensive from a performance standpoint. By removing an element from the DOM, you remove all the watchers on those elements. Having few watches in an app generally allows it to run faster.

Syntax

Ng-if, like most built-in directives relies upon evaluating an expression as true or false. In the case of ng-if, if the expression evaluates false, it removes the element from the DOM entirely (as in, the node is gone). If it’s true, the element gets recreated.

Put more simply, ng-if allows you to display or remove elements based on scope (or model) values. Even more simply: If a value is false in your model, ng-if will remove the appropriate element from the DOM (and vice versa).

Let’s see some examples:

Example #1 – Simple Hide and Show

In the example below, the model is determined by the scope boolean value showDiv. A simple ng-click on the checkbox, toggles whether showDiv is true or false.

If you hop into the developer tools, you’ll that the div is removed entirely when it is toggled off:

Before:

 

 

 

After

Pretty dang straightforward.

See the Pen Basic ng-if examples by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Example #2 – Using ng-if with ng-repeat

Here’s a fun example of ng-if being using within ng-repeat. This was made by developer Nick Moreton. This example completes the requirements for FizzBuzz, which is an old programming interview test. The test is to:

Explore Angular Courses

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

Nick shows how this can be done with a simple for loop, ng-repeat and ng-if. The page contains spans for displaying either the number, or ‘Fizz’, ‘Buzz’, or ‘FizzBuzz’. The ng-if expressions on the spans evaluate whether that element of the array is a multiple of three or five and adds or removes the element from the DOM.

See the Pen Angular FizzBuzz ng-repeat by Nick Moreton (@nickmoreton) on CodePen.


If we look again at the html in the developer tools, we can see that the DOM elements aren’t there, only html comments in there place.

 

Example #3 – ng-if with multiple conditions

You might hit a situation where you need to evaluate multiple expressions to add/remove content (effectively hiding/showing).

The JavaScript OR and AND operators (|| and &&) can be used within ng-if expressions. This allows you to test multiple values within ng-if (just like you can in code). This works much in the same way as ng-switch, but with arguably a bit simpler syntax.

The example below evaluates two properties on the model to add/remove the tag. If the person is picky, it shows their more detailed coffee preference.

See the Pen ng-if || quick example by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Caveat #1: Event Handlers and ng-if

Ng-if will completely removes the element from the DOM/page (vs. simply hiding its visibility). That means that any event handlers attached to those elements will be destroyed when they are removed. When the element is put back into place using ng-if, the event handlers will need to be attached again. However, if you use ng-click to take care of events, Angular will take care of the events for you.

Caveat #2: Child Scope and ng-if

Ng-if creates a new child scope when it adds and removes DOM nodes. The new child scope is going to inherit from the parent scope. So if something doesn’t exist in the child scope, it will then go up the inheritance chain to see if the parent has it. In many cases, you won’t notice the new scope being created. But your code/state could get confusing if you’re not aware that ng-if has create a new scope.

Explore Angular Courses

If you’re curious, Misko Hevery explains here why directives like ng-if and ng-switch create their own child scope.

Summary

Ng-if is a useful directive for adding and removing (therefore hiding/showing) content on a page. It allows for many apps to run faster but it’s not without a few caveats and potential pitfalls

About the Author:

angular.bootstrap Explained in 3 Examples

May 3rd, 2016

By default, an Angular application is initialized automatically by loading the angular.js script and placing the ng-app directive to the root element of your application (e.g. <html> tag), like the following:

<!doctype html>
<html ng-app>
<body>
  ...
  <script src="angular.js"></script>
</body>
</html>

Alternatively, you can also initialize your application manually if you need, using the angular.bootstrap() function. This is especially useful when you want your application to initialize only after a certain period or bound to another event taking place. See this page for further details about the initialization methods in Angular.

How to Use angular.bootstrap

angular.bootstrap is a function component in the core ng module that is used for starting up the Angular application manually, which gives you more control over how you initialize your application. The syntax for angular.bootstrap is as follows:

angular.bootstrap(element, [modules], [config]);

element is a DOM element (e.g. document) that is the root of the Angular application, modules (optional) is an array of modules to be loaded and config (optional) is an object used for configuration options. You can check this page on the official developer guide to read more about angular.bootstrap syntax.

Example 1: Manually Bootstrap Your Angular Application

In the following example, we manually bootstrap our application which displays a welcome message once the user logs in.

<!doctype html>
<html>
<body>
  <div ng-controller="LoginMessage">{{message}}</div>
  <script src="angular.js"></script>
  <script>
  angular.module('example', [])
  .controller('LoginMessage', function($scope) {
    $scope.message = 'Welcome to Members Area!';
  });
  angular.bootstrap(document, ['example']);
  </script>
</body>
</html>

Note how we selected document as the root of the application and how we passed the example module to the angular.bootstrap() function.

Example 2: Bootstrap by Selecting a Specific Element

In the following example, we will display the current year in our application and bootstrap it by selecting a specific element as the application root.

<!doctype html>
<html>
<body>
  <div id="year" ng-controller="Year">{{CurrentYear}}</div>
  <script src="angular.js"></script>
  <script>
  angular.module('example', [])
  .controller('Year', function($scope) {
    $scope.CurrentYear = new Date().getFullYear();
  });
  angular.bootstrap(document.getElementById('year'), ['example']);
  </script>
</body>
</html>

We selected the div element with the id #year as the root of our application.

Example 3: Bootstrap Multiple Applications

Using the angular.bootstrap function, you can bootstrap multiple angular applications on a single page. Let’s say we have two applications (app1 and app2) defined by two div elements:

<div id="app1">...</div>
<div id="app2">...</div>

We use the following code to start up these two applications:

angular.module('app1', []);
angular.module('app2', []);

angular.bootstrap(document.getElementById('app1'), ['app1']);
angular.bootstrap(document.getElementById('app2'), ['app2']);

Before ending this tutorial, we will list a number of things you should pay attention while manually starting your applications using angular.bootstrap.

  • If you use angular.bootstrap to start your application, you shouldn’t use the ng-app directive.
  • You need to create the custom modules before passing them as a parameter to angular.bootstrap().
  • When using multiple bootstraps on the same page, use them cautiously.

About the Author:

ng-class Uses Cases, Examples, and Recommendations

March 25th, 2016

ngClass is a very powerful built-in Angular directive for dynamically changing CSS classes on HTML elements. It does this by allowing us to bind scope values as class names. We can then use the state of our application (what variables are currently assigned to) to assign classes to divs, h2s, you name it.

Summed up, this directive can be used in variety of ways to change styles and hide/show content.
ngClass has a wide variety of syntaxes that take many types of expressions.  With these, you can bend ng-class to style just about anything in Angular. We’ll cover the definitions of each and explain the examples in action.

A quick note on separation of concerns

Developers who use Angular have different opinions on whether you should mix CSS classes into your JavaScript controllers. For some, this violates the principles of separation of concerns (that styling and functionality should be separate) but others are ok with it.  Some of these examples will mix CSS and JS but it’s worth knowing that not everyone does this. With some of syntaxes of ngClass, it’s almost unavoidable.

Syntax #1 – String Syntax

Definition:
The string syntax is very simple to use.  Simply put a string into the ng-class expression and that string will be used as the CSS class.
Example:

See the Pen Apply classes in angularJS using string syntax by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.


This example is pretty straightforward, the scope variable of btnClass is initiated as ‘danger’.  The ng-model of the input field is bound to the that same $scope.btnClass variable.  When a different string is put into it, the expression evaluates and checks changes the background-color if that CSS class exists.

Syntax #2 – Array Syntax

Definition: The array syntax is very similar to the array syntax except it allows for adding more than one class.  The array gets put right into the quotes in the ng-class expression.  This is helpful if you need to apply multiple classes.  You’ve probably seen a <div> with multiple classes like ‘dialog-settings template modal’.  The array syntax can be useful for this.
Example:
See the Pen AngularJS – ngClass Example by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.


Here’s a very simple example of the array syntax. By adding classes into the input boxes, you can add classes to the array thereby changing that actual CSS class on the <p> element.

Syntax #3 – Map Syntax

Definition:
Ok, here’s where it gets a lot more interesting.  The map syntax will change a CSS class according to how values get evaluated in an object.  The CSS class changes according to whether the values evaluate to a value or often to truthy/falsey.  So what the heck does this actually look like in action?
Examples:
Imagine you have this in your controller:

$scope.firstcssclass = false
$scope.secondcssclass = true
$scope.thirdcssclass = true

Then you have this in your template:

<div ng-class="{large: firstcssclass, red: secondcssclass, clear: thirdcssclass}"></div>

This would evaluate to:

<div class="red clear"></div>

So that’s a pretty basic example.  Here’s a more interesting example from a codepen by Jason McGovern.
See the Pen AngularJS ng-class conditional by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

How does this particular ng-class example work?  Let’s walk through these expressions.

ng-class="{clearance: item.clearance, new: item.salesStatus === 'new'}"

So, if you notice in the CSS, both clearance and new are CSS styles.  Item.clearance and item.salesStatus are properties on the item in the ng-repeat.  In this case, they are properties in the objects in the array $scope.products in the controller.
Here’s how these will evaluate: the items will get a class of clearance if the property of clearance is true (aka truthy).  The items will get a class of new if the property of salesStatus equals (===) true.

Syntax #4 – Ternary Syntax

The conditional ternary syntax exists in most major programming languages. In JavaScript, the syntax looks like this: condition ? expr1 : expr2.  Think of the ternary operator as a shortened way of say if (true) { do this } else {do this }.  It quickly returns a value on whether something is true or false.
The ternary syntax in Angular (released in 1.1.5, eons ago!) does a similar thing.  It is a syntax for assigning one class if an expression is truthy, and another class if the expression evaluates falsey.

ng-class="valuethatisTrueorFalse ? 'css_class_iftrue' : ‘css_class_iffalse’”>

(Mind the use of double and single quotes).
A quick example of this is this nifty bit of code from StackOverflow user Ikrom:

<span> {{userType=='admin' ? 'Edit' : 'Show'}} </span>

Here’s what this code is doing.  If the usertype of admin is true, it evaluates to the class of Edit (likely exposing something an admin would need to see).  If the admin property is set to false, the class becomes Show.  The ternary operator is helpful for examples like this where CSS classes need to be toggled.
Here’s another toggling jsfiddle example from Alex Paluzzi:

As you can see, ng-class has a lot of power in both its syntaxes and the expressions you can use in them.  It’s definitely one of the most powerful tools to have in your Angular toolkit.

About the Author:

Working With Promises in AngularJS Services

February 5th, 2016

Let’s talk about working with promises in AngularJS. To start, $q is a great implementation of promises, allowing you work with deferred objects and be more efficient with Ajax calls.

$q api has few useful methods, first one is to create new deferred object using $q.defer(), so this object could be resolve in the future using $.q.defer().resolve and also to be reject using $.defer().reject methods.

Explore Angular Courses

When executing Ajax calls from AngularJS services, usually we use $http which return by default a promise object which we can attach “then” method to for result notification.

But when the service should fetch data from the backend and allow more than one AngularJS controllers to use, it doesn’t make the make the most sense to fetch everything from the server every time. Then, we should save the data in local variable inside the service.

So when the AngularJS controller calls the service api to get the data, it could be a promise from the Ajax call or the data stored from previous call. The AngularJS controller should be able to differentiate between the cases, so thats not an ideal practice.

The way of doing it is to wrap the data stored in AngularJS service with another $q api called $q.when which can treated as a promise for both cases, so when the $q.when receive a promise it will be resolved when the promise will and if it receive a real data it will be resolved immediately.

That is transparent to the controller and this is a good practice.

Here’s a full code snippet below based on the above overview.

(function() {
  'use strict';

  angular
    .module('testApp')
    .service('testService', testService)
    .controller('testCtrl', testCtrl)
    .controller('testCtrl2', testCtrl2);

  function testService($http, $q) {

    // will hold backend posts
    var posts = undefined;

    // fetch all posts in deferred technique
    this.getPosts = function() {

      // if posts object is not defined then start the new process for fetch it
      if (!posts) {

        // create deferred object using $q
        var deferred = $q.defer();

        // get posts form backend
        $http.get('https://jsonplaceholder.typicode.com/posts')
          .then(function(result) {
            // save fetched posts to the local variable
            posts = result.data;
            // resolve the deferred
            deferred.resolve(posts);
          }, function(error) {
            posts = error;
            deferred.reject(error);
          });

        // set the posts object to be a promise until result comeback
        posts = deferred.promise;
      }

      // in any way wrap the posts object with $q.when which means:
      // local posts object could be:
      // a promise
      // a real posts data
      // both cases will be handled as promise because $q.when on real data will resolve it immediately
      return $q.when(posts);
    };

  }

  function testCtrl($scope, testService) {
    $scope.getPosts = function() {
      testService.getPosts()
        .then(function(posts) {

          console.log(posts);

        });
    };

    $scope.getPosts();
  }

  function testCtrl2($scope, testService) {
    $scope.getPosts = function() {
      testService.getPosts()
        .then(function(posts) {

          console.log(posts);

        });
    };

    $scope.getPosts();
  }

})();

Explore Angular Courses

About the Author:

The Difference Between Ng-show vs. Ng-if

September 4th, 2015

There are a variety of built-in Angular directives for showing and hiding content on a page. Ng-show/ng-hide and ng-if are commonly used directives for doing this. Ng-switch and ng-class could also be used to do this (albeit in different ways). This post will explain how ng-show and ng-if differ in their means of hiding content on a page.

https://embed.plnkr.co/eWQTdAsApBdFmvtD2ZEv/

There are two buttons in this html but only one is showing at a time. Each button has an ng-show directive on it. One button will show if the variable $scope.mute = true and the other if $scope.mute = false. This is because ng-show takes an expression as an attribute. If the expression is truthy, it shows that element on the page (and vice versa). Clicking the button there calls a function muteToggle (using ng-click) which toggles $scope.mute to true or false.

This same example could have been written with ng-hide, but with the true/false expressions reversed.

If you look at the HTML in the chrome developer tools, both buttons are there:

ng-if ng-show

You’ll notice the hidden one is set to display:none;

Screen Shot 2016-06-08 at 11.02.41 AM

Watch what happens to this same HTML if you use ng-if (which appeared in Angular 1.2) instead of ng-show.

[iframe src=”https://embed.plnkr.co/EfLFDVCgAEu8Ea66smIU” width=”100%” height=”450″]

Here’s the specific part of interest in the dev tools pane:

Screen Shot 2016-06-08 at 11.00.40 AM

Only one button shows up in the HTML now. Just like the directive sounds, that particular element (in this case, a button) will only show up if the expression is true.

Ng-show/hide can show or hide an element on a page.  They will still be in the DOM either way. Ng-if determines whether the element is actually added or removed from the DOM.

The potential problem with using ng-show/hide comes from Angular $digest loop. Ng-show can hide something from a user but not from the Angular $digest loop and watches. This can slow down performance if enough things are being watched on a page. By using ng-if, the DOM element will be removed and any watchers or event handlers with it.  The major caveat to ng-if is that it brings in its own child scope into the app. Keeping track of scopes can be confusing at times, so be warned about that part of ng-if.

There might be cases when you need to still work with things (like event handlers) that are attached to hidden elements. This would be a use case for ng-show/hide.

But the general rule of thumb here is don’t load/keep anything into the DOM that you don’t need. You should generally use ng-if unless you explicitly need ng-show/hide.

 

About the Author:

How To Get Started With AngularJS

July 13th, 2015

AngularJS is the one of the most powerful framework present for front end developing. You can develop a complete application with it. It features less boilerplate code. AngularJS is maintained by Google.

In today’s lesson I will show you a basic example of AngularJS and in this example you can observe the effectiveness of this framework.

Basics of Getting Started

AngularJS is a JavaScript framework. It is a library written in JavaScript. The first step you need to download or link to the AngularJS library.

In my case I am linking to the AngularJS URL https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js

Or you can download it from www.angularjs.org.

Good thing is you can embed it in your existing HTML code.

The ng-app directive states an AngularJS application. The ng-app directive tells AngularJS that the <div> element is the “owner” of an AngularJS application.


The ng-model directive binds the value of the input field to the application variable name. AngularJS starts automatically when the web page has loaded.

[cta id=”3157″ align=”none”]

Take a look at this example and see the magic:

The first thing you’ll notice in this template is the use of expressions (“{{“ and “}}”) to return variable values. In AngularJS, expressions allow you to execute some computation in order to return a desired value. Ultimately, they’re full blown JavaScript expressions.

In this example, {{name}} will return the value of input field having ng-model=”name”.

Looking to learn more about AngularJS for your team? Check out our custom group training options today.

About the Author:

Diving Into The Details of Two-Way Data-Binding with AngularJS

July 8th, 2015

Before we get into the details of two way data binding, let’s talk about the life cycle of an AngularJS application. So what happens when an AngularJS App loads in the browser? Well, there are three phases that it goes through:

  • The Bootstrap Phase – This is the first phase which starts when the AngularJS library (JS File) is downloaded to the browser. Now AngularJS initializes its modules and necessary components. The dependencies injected inside the module are made available to it.
  • The Compilation Phase – During the compilation phase, AngularJS replaces the static DOM (Document Object Model) with a dynamic DOM. This involves traversal of static DOM for collecting the directives, in order to link them with the scope for dynamic view.
  • The Runtime Phase – This is the final phase which lasts until the browser window is refreshed or closed. The first two phases are hardly visible to the user, and most of the time we use an Angular application, it’s in the runtime phase.

(more…)

About the Author:

Which Web Design Courses Will Best Match My Needs?

June 18th, 2015

You want to stay up-to-date with today’s web design tools, but these days it seems that there are a ton of different options out there. JavaScript, Backbone.js, Less…which tool best matches your needs and your project?

HTML and CSS Development

If you are a front-end developer looking to create a cutting edge website, make sure you consider courses in HTML5 and CSS3. HTML5 allows developers to create web-based apps that can run in any browser and adds rich multimedia capabilities. For a more extensive set of features, check out Less and Sass, preprocessors for CSS that extend the functionality of CSS with features like variables, functions, and nesting selectors, to create a more efficient and easier to maintain site.

JavaScript and Its Frameworks

JavaScript has become one of the most powerful languages for web applications. Adaptable and open source, JavaScript is both quick to learn and difficult to fully master, especially with its growing variety of toolsets. Frameworks like AngularJS, jQuery, and Ember.js will help you create interactive, robust, web applications. For back-end development, Node.js is an event-driven, server-side environment that performs I/O operations asynchronously increasing speed and functionality.

Backbone.js and Jasmine

With the complexity of modern applications, even dedicated programmers are looking for the cleanest and most productive coding techniques. Backbone.js provides organization and structure with reusable, scalable code. Courses in Jasmine will help you create behavior-driven tests to make sure complex applications run without damaging bugs or unusual behaviors.

Still not sure which courses you need? Explore the options in our catalog, then contact us at (877) 629-5631 – we’ll customize a course to meet your team’s individual goals.

About the Author:

Service Vs. Factory in AngularJS

March 28th, 2015

Service vs. Factory in AngularJS could become very confusing for users. In general, both are singleton objects for persist/share data between different parts in our application.

[test2Service] and [test2Factory] are doing exactly the same thing, and the part which uses them, refers them exactly the same (as you can see below).

The only difference between service and factory is how AngularJS treats them when requested to inject each to AngularJS part (like controller or other services, factories).

As you can see below, the factory has to return something and service is not, that means there is more flexibility when working with factories.

Factory’s return type could be a simple object or a function, and that means we can implement the factory pattern to create a new instance every time with the new keyword.

A real life showcase using this pattern could be as implemented in the [personsService] and [Person], where [personsService] hold a list of persons and we can create a new person using the [Person] factory with the keyword new.

Here’s the full code snippet we walked through:

(function() {
  'use strict';

  angular
    .module('testApp')
    .service('test2Service', test2Service)
    .factory('test2Factory', test2Factory)
    .service('personsService', personsService)
    .factory('Person', personFactory)
    .controller('test2Ctrl', test2Ctrl);

  function test2Service() {

    var persons = [
      {name:'A', lastName:'AA'},
      {name:'B', lastName:'BB'},
      {name:'C', lastName:'CC'},
      {name:'D', lastName:'DD'}
    ];

    this.getPersons = function() {
      return persons;
    }

  }

  function test2Factory() {

    var persons = [
      {name:'A', lastName:'AA'},
      {name:'B', lastName:'BB'},
      {name:'C', lastName:'CC'},
      {name:'D', lastName:'DD'}
    ];

    this.getPersons = function() {
      return persons;
    };

    return this;

  }

  function personsService(){

    var persons = [

    ];

    this.getPersons = function() {
      return persons;
    };

    this.addPerson = function(nPerson) {
      persons.push(nPerson);
    };

  }

  function personFactory() {



    return function(nName, nLastName) {
      var name = nName,
        lastName = nLastName;

      this.sayHello = function () {
        console.log("Hello from: ", lastName + ", " + name);
      };
    }
  }

  function test2Ctrl(test2Service, test2Factory, personsService, Person) {

    console.log(test2Service.getPersons());
    console.log(test2Factory.getPersons());


    console.log(personsService.getPersons());
    personsService.addPerson(new Person('foo','bar'));
    personsService.addPerson(new Person('foo2','bar2'));
    console.log(personsService.getPersons());
    angular.forEach(personsService.getPersons(), function(person) {
      person.sayHello();
    })

  }

})();

Looking to learn more about AngularJS for your team? Check out our custom group training options today.