Book Image

Learning AngularJS for .NET Developers

By : Alex Pop
Book Image

Learning AngularJS for .NET Developers

By: Alex Pop

Overview of this book

<p>AngularJS is the most popular JavaScript MVC framework, and it embraces and extends HTML rather than abstracting it. The building of single-page applications is a web-designer-friendly process with the AngularJS expressive HTML vocabulary. It drastically reduces the amount of JavaScript required to control complex user interactions and enforces a modular approach to structuring your JavaScript code.</p> <p>This book covers all of the stages of building a single-page web application, starting with frontend components powered by AngularJS, continuing with web services that leverage ServiceStack, and putting it all together in an ASP.NET MVC application. You will learn a development process focused on rapid delivery and testability for all application layers.</p>
Table of Contents (13 chapters)
Learning AngularJS for .NET Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

The JavaScript patterns and practices used in AngularJS applications


At this point, we are almost ready to discuss AngularJS in more detail. However, before doing that, we need to introduce some JavaScript patterns and practices that will be useful in understanding the rest of the content in this chapter.

One of the difficult problems to solve when writing JavaScript code is to avoid the pollution of the global scope. Any variable declared outside of a function body will automatically be visible to the global scope. You can easily imagine a scenario where your variable names clash with the variables defined in other JavaScript files or libraries. Also, JavaScript automatically moves all variable declarations to the top of the current scope. This behavior is called "hoisting" and can lead to scenarios where you use a variable before it is declared, which is confusing and can cause unintended errors.

To avoid these problems, a typical workaround is to use a function body to declare your variables. Variables declared in this way belong to the local scope of the current function, and they are invisible to the global scope. This workaround is based on two patterns used frequently in AngularJS code bases: the Immediately-invoked Function Expression (IIFE)—pronounced "iffy"—and the revealing module pattern.

Immediately-invoked Function Expression

If we append the line, console.log(myAppModule.name); at the end of the script section from the full example of the previous AngularJS application, we will see the name of the module written in the console as myApp. If we convert the example to use an Immediately-invoked Function Expression, the script section will look like the following code:

;(function(){
  var myAppModule = angular.module('myApp', []);
  myAppModule.controller('ExampleController', function ($scope) {
    $scope.name = "Alex Pop";
    $scope.previousName = "";
    $scope.onNameFocused = function() {
      $scope.previousName = $scope.name;
    };
  });
}());
console.log(myAppModule.name);

You can view the preceding example either online at http://plnkr.co/edit/A6XZfvgJITpctLEwmXC7 or in the Example5 folder from the source code for this chapter.

I have highlighted the changes required to convert the code to use the Immediately-invoked Function Expression. The leading semicolon prevents issues caused by the automatic semicolon insertions in JavaScript when your scripts get concatenated with other scripts. The enclosing parentheses after the leading semicolon and before the last semicolon are a convention for these types of expressions.

The example will still work as before, but the console output will have this message: Uncaught ReferenceError: myAppModule is not defined. Using this pattern, we made the application module invisible to the global scope, while leaving it accessible to the AngularJS infrastructure.

The revealing module pattern

The revealing module pattern solves the problem of implementation details being hidden for JavaScript objects that need to provide publicly accessible properties. The following example is a plain JavaScript one—no external library references are required:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Chapter1 Example6</title>
</head>
<body>
  <h1>Revealing module pattern</h1>
  <script>
    var revealingModule = (function() {
      var innerObject = 5;
      var innerFunction = function(value) {
        return innerObject + value;
      };
      return {
        outerObject1: innerFunction(1),
        outerObject2: innerFunction(2),
        outerFunction: innerFunction
      };
    }());
    console.log("outerObject1:" + revealingModule.outerObject1);
    console.log("outerObject2:" + revealingModule.outerObject2);
    console.log("innerObject:" + revealingModule.innerObject);
    console.log("outerFunction(3):" + revealingModule.outerFunction(3));
    console.log("innerFunction(3):" + revealingModule.innerFunction(3));
  </script>
</body>
</html>

You can view the example either online at http://plnkr.co/edit/AFbIj5YQO64N9sKYF19u or in the Example6 folder from the source code for this chapter.

I have highlighted the revealing module pattern, and you will notice that it relies on an IIFE to define itself. Using this pattern, all of the variables declared inside of the IIFE are inaccessible to the outside scope, and the only visible properties are the ones returned in the last statement. The console output for this example is the following:

outerObject1:6
outerObject2:7
innerObject:undefined
outerFunction(3):8
Uncaught TypeError: Object #<Object> has no method 'innerFunction'

Any reference to the variables defined within the IIFE will be unsuccessful, even if the property exposed is a direct reference to an inner variable like the outerFunction property. You will see this pattern in action throughout the rest of the examples of this book.

Note

You can find more information about the revealing module pattern and other JavaScript design patterns in the online resource Learning JavaScript Design Patterns, Addy Osmani, O'Reilly Media, available at http://addyosmani.com/resources/essentialjsdesignpatterns/book.

The strict mode of JavaScript

The JavaScript standard ECMAScript 5 has introduced a new way to use a stricter variant of JavaScript. This variant changes the behavior of the JavaScript runtime, and the following are some changes that occur in strict mode:

  • Some silent errors are thrown instead of being ignored, such as assignment to a nonwritable property.

  • All global variables need to be explicitly declared. When you mistype a global variable name, an exception is thrown.

  • All of the property names of an object need to be unique, and all of the parameter names for a function also need to be unique.

By including the line "use strict"; in your scripts, you can adhere to the ECMAScript 5 strict mode when using a modern browser. If the script is loaded in an older browser, the statement is ignored and the JavaScript is parsed in non-strict mode. Strict mode can only be safely declared at the top of a function body. If it is declared in the global scope, it can cause issues when a strict mode script is concatenated with other non-strict scripts.

Using strict mode leads to safer, cleaner code with fewer errors. It is now common practice that any AngularJS script will be enclosed by an IIFE with strict mode enabled.

All AngularJS examples throughout the rest of the book will use the patterns discussed in this section.