Learning AngularJS on Single Page Applications

Single Page Application (SPA) :

is an app that only requires a browser to load just a single page. The browser wont have the burden to reload the page anymore on every minimal interactions that the user makes and instead, focus only on the things that required changes.

Modules :
You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc.

Most applications have a main method that instantiates and wires together the different parts of the application.

Angular apps don’t have a main method. Instead modules declaratively specify how an application should be bootstrapped. There are several advantages to this approach:

  • The declarative process is easier to understand.
  • You can package code as reusable modules.
  • The modules can be loaded in any order (or even in parallel) because modules delay execution.
  • Unit tests only have to load relevant modules, which keeps them fast.
  • End-to-end tests can use modules to override configuration.
  • Declairing a module :
  • // declare a module
    angular.module(‘module-name’,[dependencies]);
    
  • Important things to notice:
  • The reference to module “module-name” in

    <html ng-app="module-name">

    . This is what bootstraps the app using your module.
    Every module should have a name, which is specified in the first parameter. Second parameter to module function is an array, which may contain names of other modules or services. If the module doesn’t depend on anything, the array can be left blank.

  • Module Loading & Dependencies :
  • A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:

  • Configuration blocks
  • get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

  • Run blocks
  • get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

    angular.module('myModule', []).
      config(function(injectables) { // provider-injector
        // This is an example of config block.
        // You can have as many of these as you want.
        // You can only inject Providers (not instances)
        // into config blocks.
      }).
      run(function(injectables) { // instance-injector
        // This is an example of a run block.
        // You can have as many of these as you want.
        // You can only inject instances (not Providers)
        // into run blocks
      });
    
  • Configuration Blocks
  • There are some convenience methods on the module which are equivalent to the config block. For example:

    angular.module('myModule', []).
      value('a', 123).
      factory('a', function() { return 123; }).
      directive('directiveName', ...).
      filter('filterName', ...);
    
    // is same as
    
    angular.module('myModule', []).
      config(function($provide, $compileProvider, $filterProvider) {
        $provide.value('a', 123);
        $provide.factory('a', function() { return 123; });
        $compileProvider.directive('directiveName', ...);
        $filterProvider.register('filterName', ...);
      });
    

    When bootstrapping, first Angular applies all constant definitions. Then Angular applies configuration blocks in the same order they were registered.

  • Run Blocks
  • Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

  • Dependencies
  • Modules can list other modules as their dependencies. Depending on a module implies that required module needs to be loaded before the requiring module is loaded. In other words the configuration blocks of the required modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

    For more info https://docs.angularjs.org/guide/module

    Directives :

    Directives are attribute-like code in the html page that is only understandable by AngularJS.
    Various angular directives are ng-app, ng-controller, ng-click, ng-repeat etc. Using these we can build highly interactive and dynamic website.

  • ng-app
  • The first directive that we need to know is the ng-app. This directive tells the AngularJS compiler that the page is an angular module/application.
    We must put the directive “ng-app” to the parent tag. The best practice is to put the said directive in the root tag of the document which is . It is much readable and can be noticed easily if it’s placed there.

    ng-app defines the code block that is controlled by AngularJS. In most of the real time scenarios, we may need to write our own filters, define routing for our application or define new directive for our application. So we need to customize angular for our needs and ng-app is the place for that. Till now we have used parameterless ng-app directive, which bootstraps the default angular behavior on our application. We will look into ng-app with parameter, called application module A single page can have only one ng-app directive. (If we bootstrap manually, it is possible to have multiple ng-app, but it is not advised).

    //Only one ngApp directive can be used per HTML Document.
    
    //You can inject the second module as a dependency to the first module:
    
    var shoppingCartModule = angular.module("shoppingCart", ["namesList"]);
    
    //And in the HTML wrap the contents inside a single element with ng-app:
    
    <html>
    <body>
    <div ng-app="shoppingCart" ng-controller="ShoppingCartController">
        <h1>Your order</h1>
    </div>
    </body>
    </html>
    
  • ng-controller
  • This attribute defines a Controller to be bound with the view. In this case we defined a controller called ContactController in DIV using ng-controller attribute. Thus whatever we put inside that DIV, the ContactController will have its influence on it.

    <!DOCTYPE html>
    <html ng-app>
    <head>
    <title>Hello World, AngularJS</title>
    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    </head>
    <body>
    <div ng-controller="ContactController"> 
    </div>
    </body>
    </html>
    

    ContactController is nothing but a plain vanilla JavaScript function. In the demo we defined it as function. Also see the definition of ContactController function. There is an object $scope which we pass as an argument. This object is used to bind the controller with view. When AngularJS initialize this controller, it automatically creates and injects the $scope object to this function using dependency injection (More on dependency injection in coming tutorials). For now just note that the $scope object is created by Angular and injected in this controller function.

    var myApplication=angular.module('myApp',[]);
    
    myApplication.controller('ContactController',
                             ['$scope', '$filter', function (s, f) {
                                s.name = 'manas';
                                s.nameUpper = f('uppercase')(s.name);
           }]);
    
  • ng-click
  • It is also possible to define functions on $scope inside controller and use the same in View. In our demo, we created a function add() on $scope and use it on Add button click:

    
    //in html file
    <!DOCTYPE html>
    <html>
      <head>
    <script src="js/app.js"></script>
        <script src="js/controllers.js"></script>
      </head>
      <body ng-app="starter">
        <div id='content' ng-controller='mainController'>
               <button ng-click='sayAlert("mate")'>Hello</button>
      </div>
    </body>
    </html>
    
    //in controllers.js
    angular.module('controllerModule', [])
    
    .controller('mainController', function($scope) {
    	$scope.understand = "I now understand how the scope works!";
    	$scope.sayAlert = function(helloString){
    		alert("hi "+helloString);
    	 }
    });
    

    The function add() is bound to Add button using an attribute ng-click. ng-click binds the click event on the button or link or any clickable element with the function that is defined within $scope. So in this case, whenever Add button is clicked, the add() method on $scope will be called.

    Scopes :

    Scope is nothing but an object that Glues the View with Controller. They hold the Model data that we need to pass to view. Scope uses Angular’s two-way data binding to bind model data to view.

    Imaging $scope as an object that links Controller to the View. It is controllers responsibility to initialize the data that the view needs to display. This is done by making changes to $scope.

    Let us see a small Hello World application to understand $scope.

    <!DOCTYPE html>
    <html ng-app>
    <head>
    <title>Hello World, AngularJS - ViralPatel.net</title>
    <script type="text/javascript"
        src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    </head>
    <body>
    <div ng-controller="ContactController">
         Email:<input type="text" ng-model="newcontact"/>
        <button ng-click="add()">Add</button>
        <h2>Contacts</h2>
     
        <ul>
            <li ng-repeat="contact in contacts"> {{ contact }} </li>
        </ul>
     
    </div>
    <script type="text/javascript">
        function ContactController($scope) {
            $scope.contacts = ["hi@email.com", "hello@email.com"];
     
            $scope.add = function() {
            $scope.contacts.push($scope.newcontact);
            $scope.newcontact = "";
            }
        }
    </script>
    </body>
    </html>
    

    Relation between all these :

    service

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s