Tuesday, September 22, 2015

AngularJS Introduction


AngularJS 1.5

Directive is a marker on an HTML tag that tells Angular to run or reference some Javascript code.

HTML page:
<html ng-app="studentModule">
<head>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
</head>
<body class="container" ng-controller="StudentController as s">
    <ul class="list group">
        <li class="list group item" ng-repeat="student in s.students">
            <h3>
                {{student.firstName}} {{student.lastName}}
                <em class="pull-right">{{student.emailId}}</em>
            </h3>
        </li>
    </ul>
</body>
</html>
Javascript:
(function() {
  var app = angular.module('studentModule', []);

  app.controller('StudentController', ['$http', function($http){
    var store = this;
    store.students = [];

    $http.get("/api/students").success(function(data) {
        store.students = data;
    });
  }]);
})();

Here ng-controller is the directive.

Modules: is where we write pieces of our Angular application and define dependencies for our app. Modules can use other modules (or depend on other modules).

Var app = angular.module('store', []) -- define a new module named 'store' and with no dependencies (so empty array) -- this goes into a separate app.js

-- ng-app directive will run the module named "store" when the document loads. Ng-app also makes the entire html page an angular application which means the contents within can now use the features of the angular framework - like writing expression such as:

I am {{4 + 6 }}

Will translate to:

I am 10


Similarly we can have string expressions: {{ "hello" + " world" }}

We can have filters in the expression by using pipe to get the o/p of expression as input of a filter and thus achieve filtered result:
{{ product.price | currency }}

Or in general: {{ data* | filter: options*}}

date

uppercase
lowercase

limitTo

orderBy


Sample 1:

Controllers: where we define our app's behavior.

//Wrapthejavascriptinaclosure(function(){})();
(function(){
varapp=angular.module('store',[]);

//Defineourcontroller,theanonymousfunctioniswhatgetscalledwhenourcontrollerisinvoked.
app.controller('StoreController',function(){
//setproperty-producttothedata.
this.product=gem;
});

//data
vargem={
name:'Dodecahedron',
price:2.95,
description:'...',
}
})();
The purpose of the controller is to get the JSON data (from gem object in this case) over to html page block where the ng-controller is defined. This way we can get the JSON data into a javascript client side object in some way (say by querying REST endpoint) and then populate the div block in the html page with the data - and this is facilitated by the controller's property ("product" in this case) which is set to JSON javascript object (gem in this case).

html>
<htmllang="en"ng-app="store">
<head>
<metacharset="UTF-8">
<title></title>
<linkrel="stylesheet"type="text/css"href="css/bootstrap.min.css"/>

</head>
<body>
<divng-controller="StoreControllerasstore">
<h1>{{store.product.name}}</h1>
<h2>{{store.product.price}}</h2>
<p>{{store.product.description}}</p>
</div>
<scripttype="text/javascript"src="js/angular.min.js"></script>
<scripttype="text/javascript"src="js/app.js"></script>
</body>
</html>
Built-in validations for common input types:
Email, url, number (max, min),

  Directives

Monday, September 21, 2015
1:27 PM
Directives:
<htmlng-app="studentModule">
Attach application module to a page
<bodyclass="container"ng-controller="StudentController">
Attach a controller function to the page
<divclass="productrow"ng-repeat="studentinstudents">
Repeat a section of the page for each item in an array
ng-show/ng-hide
Display or not display a section based on an expression
ng-source
Ng-click
Ng-class
Will set to the classname when condition specified is true.
Ng-class="active:tab === 1"
Ng-model - binds the form elements to properties -- this is how we create a live preview.
Ng-submit - specify method to invoke when form is submitted.

Ng-include - include html snippet



Custom Directives - makes html more readable.. Same can be achieved using ng-include directive by including the duplicating snippet of html code from another html file. But custom directives will be like new tags -

 Modules

Tuesday, September 22, 2015
12:02 AM
App.js - root module "store" is defined here that is referred in our single page app's html page (with ng-app directive). It will have dependencies on all other sub-modules.

var app = angular.module("store", ["products-directives"])

Products.js - can be another module consisting of custom directives (which also might encapsulate controllers) pertaining to products in the store.

..
And so on, there could be other modules which are referred by products module or by the main store module.

Services
Tuesday, September 22, 2015
12:06 AM
Services give controllers additional functionality.
  1. Fetching JSON from webservice - $http
  2. Logging message for Javascript console - $log
  3. Filtering an array - $filter

$http

$http({ method: 'GET',  url: '/products.json' });
Or
$http.get('/products.json', {apiKey: 'myApiKey'… other query params});

Returns a promise object: .success() or .error()


$http.post('/api/students',  {param: 'value'});

$http.delete('/api/students');


No comments:

Popular micro services patterns

Here are some popular Microservice design patterns that a programmer should know: Service Registry  pattern provides a  central location  fo...