AngularJS

Getting started with AngularJS

Remarks#

AngularJS is a web application framework designed to simplify rich client-side application development. This documentation is for Angular 1.x, the predecessor of the more modern Angular 2 or see the Stack Overflow documentation for Angular 2.

Versions#

VersionRelease Date
1.6.52017-07-03
1.6.42017-03-31
1.6.32017-03-08
1.6.22017-02-07
1.5.112017-01-13
1.6.12016-12-23
1.5.102016-12-15
1.6.02016-12-08
1.6.0-rc.22016-11-24
1.5.92016-11-24
1.6.0-rc.12016-11-21
1.6.0-rc.02016-10-26
1.2.322016-10-11
1.4.132016-10-10
1.2.312016-10-10
1.5.82016-07-22
1.2.302016-07-21
1.5.72016-06-15
1.4.122016-06-15
1.5.62016-05-27
1.4.112016-05-27
1.5.52016-04-18
1.5.42016-04-14
1.5.32016-03-25
1.5.22016-03-19
1.4.102016-03-16
1.5.12016-03-16
1.5.02016-02-05
1.5.0-rc.22016-01-28
1.4.92016-01-21
1.5.0-rc.12016-01-16
1.5.0-rc.02015-12-09
1.4.82015-11-20
1.5.0-beta.22015-11-18
1.4.72015-09-30
1.3.202015-09-30
1.2.292015-09-30
1.5.0-beta.12015-09-30
1.5.0-beta.02015-09-17
1.4.62015-09-17
1.3.192015-09-17
1.4.52015-08-28
1.3.182015-08-19
1.4.42015-08-13
1.4.32015-07-15
1.3.172015-07-07
1.4.22015-07-07
1.4.12015-06-16
1.3.162015-06-06
1.4.02015-05-27
1.4.0-rc.22015-05-12
1.4.0-rc.12015-04-24
1.4.0-rc.02015-04-10
1.3.152015-03-17
1.4.0-beta.62015-03-17
1.4.0-beta.52015-02-24
1.3.142015-02-24
1.4.0-beta.42015-02-09
1.3.132015-02-09
1.3.122015-02-03
1.4.0-beta.32015-02-03
1.3.112015-01-27
1.4.0-beta.22015-01-27
1.4.0-beta.12015-01-20
1.3.102015-01-20
1.3.92015-01-15
1.4.0-beta.02015-01-14
1.3.82014-12-19
1.2.282014-12-16
1.3.72014-12-15
1.3.62014-12-09
1.3.52014-12-02
1.3.42014-11-25
1.2.272014-11-21
1.3.32014-11-18
1.3.22014-11-07
1.3.12014-10-31
1.3.02014-10-14
1.3.0-rc.52014-10-09
1.2.262014-10-03
1.3.0-rc.42014-10-02
1.3.0-rc.32014-09-24
1.2.252014-09-17
1.3.0-rc.22014-09-17
1.2.242014-09-10
1.3.0-rc.12014-09-10
1.3.0-rc.02014-08-30
1.2.232014-08-23
1.3.0-beta.192014-08-23
1.2.222014-08-12
1.3.0-beta.182014-08-12
1.2.212014-07-25
1.3.0-beta.172014-07-25
1.3.0-beta.162014-07-18
1.2.202014-07-11
1.3.0-beta.152014-07-11
1.2.192014-07-01
1.3.0-beta.142014-07-01
1.3.0-beta.132014-06-16
1.3.0-beta.122014-06-14
1.2.182014-06-14
1.3.0-beta.112014-06-06
1.2.172014-06-06
1.3.0-beta.102014-05-24
1.3.0-beta.92014-05-17
1.3.0-beta.82014-05-09
1.3.0-beta.72014-04-26
1.3.0-beta.62014-04-22
1.2.162014-04-04
1.3.0-beta.52014-04-04
1.3.0-beta.42014-03-28
1.2.152014-03-22
1.3.0-beta.32014-03-21
1.3.0-beta.22014-03-15
1.3.0-beta.12014-03-08
1.2.142014-03-01
1.2.132014-02-15
1.2.122014-02-08
1.2.112014-02-03
1.2.102014-01-25
1.2.92014-01-15
1.2.82014-01-10
1.2.72014-01-03
1.2.62013-12-20
1.2.52013-12-13
1.2.42013-12-06
1.2.32013-11-27
1.2.22013-11-22
1.2.12013-11-15
1.2.02013-11-08
1.2.0-rc.32013-10-14
1.2.0-rc.22013-09-04
1.0.82013-08-22
1.2.0rc12013-08-13
1.0.72013-05-22
1.1.52013-05-22
1.0.62013-04-04
1.1.42013-04-04
1.0.52013-02-20
1.1.32013-02-20
1.0.42013-01-23
1.1.22013-01-23
1.1.12012-11-27
1.0.32012-11-27
1.1.02012-09-04
1.0.22012-09-04
1.0.12012-06-25
1.0.02012-06-14
v1.0.0rc122012-06-12
v1.0.0rc112012-06-11
v1.0.0rc102012-05-24
v1.0.0rc92012-05-15
v1.0.0rc82012-05-07
v1.0.0rc72012-05-01
v1.0.0rc62012-04-21
v1.0.0rc52012-04-12
v1.0.0rc42012-04-05
v1.0.0rc32012-03-30
v1.0.0rc22012-03-21
g3-v1.0.0rc12012-03-14
g3-v1.0.0-rc22012-03-16
1.0.0rc12012-03-14
0.10.62012-01-17
0.10.52011-11-08
0.10.42011-10-23
0.10.32011-10-14
0.10.22011-10-08
0.10.12011-09-09
0.10.02011-09-02
0.9.192011-08-21
0.9.182011-07-30
0.9.172011-06-30
0.9.162011-06-08
0.9.152011-04-12
0.9.142011-04-01
0.9.132011-03-14
0.9.122011-03-04
0.9.112011-02-09
0.9.102011-01-27
0.9.92011-01-14
0.9.72010-12-11
0.9.62010-12-07
0.9.52010-11-25
0.9.42010-11-19
0.9.32010-11-11
0.9.22010-11-03
0.9.12010-10-27
0.9.02010-10-21

Getting Started

Create a new HTML file and paste the following content:

<!DOCTYPE html>
<html ng-app>
<head>
  <title>Hello, Angular</title>
  <script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
</head>
<body ng-init="name='World'">
  <label>Name</label>
  <input ng-model="name" />
  <span>Hello, {{ name }}!</span>
  <p ng-bind="name"></p>
</body>
</html>

Live demo

When you open the file with a browser, you will see an input field followed by the text Hello, World!. Editing the value in the input will update the text in real-time, without the need to refresh the whole page.


Explanation:

  1. Load the Angular framework from a Content Delivery Network.

    <script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
  2. Define the HTML document as an Angular application with the ng-app directive

    <html ng-app>
  3. Initialize the name variable using ng-init

    <body ng-init=" name = 'World' ">

    Note that ng-init should be used for demonstrative and testing purposes only. When building an actual application, controllers should initialize the data.

  4. Bind data from the model to the view on HTML controls. Bind an <input> to the name property with ng-model

    <input ng-model="name" />
  5. Display content from the model using double braces {{ }}

    <span>Hello, {{ name }}</span>
  6. Another way of binding the name property is using ng-bind instead of handlebars"{{ }}"

     <span ng-bind="name"></span>

The last three steps establish the two way data-binding. Changes made to the input update the model, which is reflected in the view.

There is a difference between using handlebars and ng-bind. If you use handlebars, you might see the actual Hello, {{name}} as the page loads before the expression is resolved (before the data is loaded) whereas if you use ng-bind, it will only show the data when the name is resolved. As an alternative the directive ng-cloak can be used to prevent handlebars to display before it is compiled.

Showcasing all common Angular constructs

The following example shows common AngularJS constructs in one file:

<!DOCTYPE html>
<html ng-app="myDemoApp">
  <head>
    <style>.started { background: gold; }</style>
    <script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
    <script>
      function MyDataService() {
        return {
          getWorlds: function getWorlds() {
            return ["this world", "another world"];
          }
        };
      }

      function DemoController(worldsService) {
        var vm = this;
        vm.messages = worldsService.getWorlds().map(function(w) {
          return "Hello, " + w + "!";
        });
      }

      function startup($rootScope, $window) {
        $window.alert("Hello, user! Loading worlds...");
        $rootScope.hasStarted = true;
      }
      
      angular.module("myDemoApp", [/* module dependencies go here */])
        .service("worldsService", [MyDataService])
        .controller("demoController", ["worldsService", DemoController])
        .config(function() {
          console.log('configuring application');
        })
        .run(["$rootScope", "$window", startup]);
    </script>
  </head>
  <body ng-class="{ 'started': hasStarted }" ng-cloak>
    <div ng-controller="demoController as vm">
      <ul>
        <li ng-repeat="msg in vm.messages">{{ msg }}</li>
      </ul>
    </div>
  </body>
</html>

Every line of the file is explained below:

Live Demo

  1. ng-app="myDemoApp", the ngApp directive that bootstraps the application and tells angular that a DOM element is controlled by a specific angular.module named "myDemoApp";
  2. <script src="angular.min.js"> is the first step in bootstrapping the AngularJS library;

Three functions (MyDataService, DemoController, and startup) are declared, which are used (and explained) below.

  1. angular.module(...) used with an array as the second argument creates a new module. This array is used to supply a list of module dependencies. In this example we chain calls on the result of the module(...) function;

  2. .service(...) creates an Angular Service and returns the module for chaining;

  3. .controller(...) creates an Angular Controller and returns the module for chaining;

  4. .config(...) Use this method to register work which needs to be performed on module loading.

  5. .run(...) makes sure code is run at startup time and takes an array of items as a parameter. Use this method to register work which should be performed when the injector is done loading all modules.

    • the first item is letting Angular know that the startup function requires the built-in $rootScope service to be injected as an argument;
    • the second item is letting Angular know that the startup function requires the built-in $window service to be injected as an argument;
    • the last item in the array, startup, is the actual function to run on startup;
  6. ng-class is the ngClass directive to set a dynamic class, and in this example utilizes hasStarted on the $rootScope dynamically

  7. ng-cloak is a directive to prevent the unrendered Angular html template (e.g. ”{{ msg }}”) to be briefly shown before Angular has fully loaded the application.

  8. ng-controller is the directive that asks Angular to instantiate a new controller of specific name to orchestrate that part of the DOM;

  9. ng-repeat is the directive to make Angular iterate over a collection and clone a DOM template for each item;

  10. {{ msg }} showcases interpolation: on-the-spot rendering of a part of the scope or controller;

The importance of scope

As Angular uses HTML to extend a web page and plain Javascript to add logic, it makes it easy to create a web page using ng-app, ng-controller and some built-in directives such as ng-if, ng-repeat, etc. With the new controllerAs syntax, newcomers to Angular users can attach functions and data to their controller instead of using $scope.

However, sooner or later, it is important to understand what exactly this $scope thing is. It will keep showing up in examples so it is important to have some understanding.

The good news is that it is a simple yet powerful concept.

When you create the following:

<div ng-app="myApp">
 <h1>Hello {{ name }}</h1>
</div>

Where does name live?

The answer is that Angular creates a $rootScope object. This is simply a regular Javascript object and so name is a property on the $rootScope object:

angular.module("myApp", [])
  .run(function($rootScope) {
    $rootScope.name = "World!";
  });

And just as with global scope in Javascript, it’s usually not such a good idea to add items to the global scope or $rootScope.

Of course, most of the time, we create a controller and put our required functionality into that controller. But when we create a controller, Angular does it’s magic and creates a $scope object for that controller. This is sometimes referred to as the local scope.

So, creating the following controller:

<div ng-app="myApp">
  <div ng-controller="MyController">
    <h1>Hello {{ name }}</h1>
  </div>
</div>

would allow the local scope to be accessible via the $scope parameter.

angular.module("myApp", [])
  .controller("MyController", function($scope) {
    $scope.name = "Mr Local!";
  });

A controller without a $scope parameter may simply not need it for some reason. But it is important to realize that, even with controllerAs syntax, the local scope exists.

As $scope is a JavaScript object, Angular magically sets it up to prototypically inherit from $rootScope. And as you can imagine, there can be a chain of scopes. For example, you could create a model in a parent controller and attach to it to the parent controller’s scope as $scope.model.

Then via the prototype chain, a child controller could access that same model locally with $scope.model.

None of this is initially evident, as it’s just Angular doing its magic in the background. But understanding $scope is an important step in getting to know how Angular works.

The Simplest Possible Angular Hello World.

Angular 1 is at heart a DOM compiler. We can pass it HTML, either as a template or just as a regular web page, and then have it compile an app.

We can tell Angular to treat a region of the page as an expression using the {{ }} handlebars style syntax. Anything between the curly braces will be compiled, like so:

{{ 'Hello' + 'World' }}

This will output:

HelloWorld

ng-app

We tell Angular which portion of our DOM to treat as the master template using the ng-app directive. A directive is a custom attribute or element that the Angular template compiler knows how to deal with. Let’s add an ng-app directive now:

<html>
  <head>
    <script src="/angular.js"></script>
  </head>
  <body ng-app>
    {{ 'Hello' + 'World' }}
  </body>
</html>

I’ve now told the body element to be the root template. Anything in it will be compiled.

Directives

Directives are compiler directives. They extend the capabilities of the Angular DOM compiler. This is why Misko, the creator of Angular, describes Angular as:

“What a web browser would have been had it been built for web applications.

We literally create new HTML attributes and elements, and have Angular compile them into an app. ng-app is a directive that simply turns on the compiler. Other directives include:

  • ng-click, which adds a click handler,
  • ng-hide, which conditionally hides an element, and
  • <form>, which adds additional behaviour to a standard HTML form element.

Angular comes with around 100 built-in directives which allow you to accomplish most common tasks. We can also write our own, and these will be treated in the same way as the built in directives.

We build an Angular app out of a series of directives, wired together with HTML.

Minification in Angular

What is Minification ?

It is the process of removing all unnecessary characters from source code without changing its functionality.

Normal Syntax

If we use normal angular syntax for writing a controller then after minifiying our files it going to break our functionality.

Controller (Before minification) :

var app = angular.module('mainApp', []);    
app.controller('FirstController', function($scope) {
    $scope.name= 'Hello World !';  
});

After using minification tool, It will be minified as like below.

var app=angular.module("mainApp",[]);app.controller("FirstController",function(e){e.name= 'Hello World !'})

Here, minification removed unnecessary spaces and the $scope variable from code. So when we use this minified code then its not going to print anything on view. Because $scope is a crucial part between controller and view, which is now replaced by the small ‘e’ variable. So when you run the application it is going to give Unknown Provider ‘e’ dependency error.

There are two ways of annotating your code with service name information which are minification safe:

Inline Annotation Syntax

var app = angular.module('mainApp', []);    
app.controller('FirstController', ['$scope', function($scope) {
    $scope.message = 'Hello World !'; 
}]);

$inject Property Annotation Syntax

FirstController.$inject = ['$scope'];
var FirstController = function($scope) {
    $scope.message = 'Hello World !'; 
}

var app = angular.module('mainApp', []);
app.controller('FirstController', FirstController);

After minification, this code will be

var app=angular.module("mainApp",[]);app.controller("FirstController",["$scope",function(a){a.message="Hello World !"}]);

Here, angular will consider variable ‘a’ to be treated as $scope, and It will display output as ‘Hello World !‘.

AngularJS Getting Started Video Tutorials

There are a lot of good video tutorials for the AngularJS framework on egghead.io

enter image description here


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow