AngularJS Basics

Tomasz Szewców

Agenda

  1. Environment preparation
  2. Angular Modules
  3. Dependency Injection
  4. Controllers
  5. Services and Factories
  6. Useful Directives
  7. Backend Communication
  8. Routing

Setting up the OASP4JS application template

  • Install the necessary tools: Node.js, Bower and Gulp.
  • Open the command line tool and do the following:

		# install the Yoeman globally using Node Package Manager
npm install -g yo
# install the OASP template generator-oasp globally
npm install -g generator-oasp
# make a directory for the template and navigate to it
mkdir directory_name
cd directory_name
# Call the generator in the selected directory
yo oasp
# start the app using gulp
gulp serve
		

https://github.com/oasp/generator-oasp

What is an Angular module?

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

https://docs.angularjs.org/guide/module

Module definition and retrieval


        // define a module without dependencies
angular.module('moduleName', []);
		
// define a module with dependencies
angular.module('moduleName', ['dependency1', 'dependency2']);
		
// retrieve a module
angular.module('moduleName');
      

        

Dependency Injection

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies.
The Angular injector subsystem is in charge of creating components, resolving their dependencies, and providing them to other components as requested.

https://docs.angularjs.org/guide/di

Injecting dependencies


	angular.module('moduleName').controller('SomeController', function($scope, someService){
	'use strict';
	
	// add something to injected $scope
	$scope.data = {};
		
	// call injected service method
	someService.someMethod();
};
	

Controller recipe


	angular.module('someModule').controller('MyFirstController', function($scope){
    'use strict';

    $scope.helloWorld = 'hello world!';
    alert($scope.helloWorld);
});
		


<!DOCTYPE html>
<html>
    <body>
        <section data-ng-controller="MyFirstController">
            <h2>Hello from Dialog A!</h2>
        </section>
    </body>
</html>
		  

Service recipe (with service)


angular.module('someModule').service('myService', function(){
    'use strict';
        
    this.print = function(){
        alert('hello world from a service');
    };
});
		  

Service recipe (with factory)


angular.module('someModule').factory('myService2', function(){
    'use strict'; 
        
    var helloWorld = 'hello world from a service2';

    return {
        print: function(){
            alert(helloWorld);
        }
    };

});
		  

Useful built-in directives

  • ngBind - one way binding
  • ngModel - two way binding
  • ngClick - calling an action
  • ngForm - instatiates FromController
  • ngRequired - adds the required validator
  • ngPattern - adds the pattern validator

Useful built-in directives

  • ngDisabled - adds the disabled attribute to a HTML element
  • ngReadonly - adds the readonly attribute to a HTML element
  • ngRepeat - repeats the HTML element
  • ngShow / ngHide - showing / hiding HTML element
  • ngIf - removes or recreates a portion of DOM
  • ngClass - applies css classes to a HTML element

Backend communication with $http service


		  // Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
  
// shortcut methods
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
			

https://docs.angularjs.org/api/ng/service/$http

Response object

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

https://docs.angularjs.org/api/ng/service/$http

Simple routing


angular.module('moduleName', []).config(function ($routeProvider) {
    $routeProvider.when('/tables', {
        templateUrl: '/table-mgmt/html/tables.html',
        controller: 'TablesCntl'
    }).when('/table-view', {
        templateUrl: '/table-mgmt/html/table-details.html',
        controller: 'TableDetailsCntl'
    });
});
        

Routing with initial data


angular.module('moduleName', []).config(function ($routeProvider) {
    $routeProvider.when('/books', {
        templateUrl: '/table-mgmt/html/tables.html',
        controller: 'TablesCntl',
        resolve: {
	    // the 'tables' function is injectable
            tables: function(){
                //return data or promise and inject into controller
            }
        }
});
        

Exercise

  • Use OASP4JS template to write a small client side app for books management
  • Application should consist of 3 dialogs - book list (modeless) + 2 modal dialogs for adding a book and editing a book
  • Book list dialog should load data from json file with $http get
  • Books in the list should be selecteble
  • Selecting a book enables Edit button which calls modal with loaded data
  • Add button is always available and calls modal with empty form
  • Title and Author fields are required while modyfying / adding a book
  • Send the post / put on book add / update - just send the requests, there is no need to handle them
  • All $http operations should be wrapped in an angular service which should be later on injected into controllers
  • Use AngularUI modal and Bootrap CSS classes