Hi, this is PJ MARTIN

Lately I got curious about Angular JS framework and decided to give it a try.

Angular JS is a javascript MVC framework which features Double Data Binding between model and view.
Its routing engine is great for making (multi-screen) Single Page Application.

I have just learned the basics from this tutorial
https://www.airpair.com/angularjs/posts/angularjs-tutorial
and made my own example page to conjugate everything.
But in this first blog post I will introduce only the basic concepts.

After making a brief overview of Angular Concepts, I’ll first introduce a first “Hello World” example, then I will give some filters example.

Overview

Angular JS lets you handle the MVC architecture with a set of sub-concepts that I am gonna introduce today.
The MVC (Model-View-Control) architecture is handled by the following Angular JS components :

Model (service, factory)
View (html page Element with angular directives and filters)
Controller (scope, controller, contollerAs)

A minimal example “Hello World”

Let’s see a minimal example of data binding using the minimum angular code (no controller).
Make 2 files HelloWorld.html and HelloWorld.js and write the following code :

Hello World Source Code

HelloWorld.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Casley Consulting Angular tutorial </title>
<script src="http://code.angularjs.org/1.3.0-beta.17/angular.min.js"></script><!--➁-->
<script src="HelloWorld.js"></script>
</head>
<body ng-app="HelloWorldApp"><!--➃-->
<p> When you change something here, </p>
<input type="text" placeholder="Please input something here" ng-model="hello" ng-init="hello='Hello World'" /><!--➀-->
<p> the change is reflected here as well : {{ hello }}</p><!--➀-->
<p> The text above is {{ hello.length }}<!--➀-->characters long</p>
</body>
</html>

HelloWorld.js

angular.module("HelloWorldApp",[]);//➂

Understanding the Source

This small angular app has a text field which data is bind to some text below.
If you change the text field value Angular automatically pushes the changes to the text below.

The text field has a ng-model attribute that defines a variable named “hello” in Angular $scope.
The paragraph below it uses the same variable named hello with angular variable display syntax {{ hello }}

As long as it is the same variable name in the same scope(➀), any change makes Angular binding update its value everywhere it is used.
For example hello.length gets updated right away too with the dynamic number of characters as you type.

In order to do that, you just need to do the following things :
– Include angular js script (➁)

– Declare the angular module in javascript (➂)
Here you use the “module” setter of the angular object to register a module named “HelloWorldApp” and that depends on no module : empty array “[]”. For complex apps you can depend on other modules (for example the routing module) that you declare in this array.

– Use the ng-app directive ➃ to tell your body element to use the angular module : ng-app=”HelloWorldApp”
Note : you could use the directive on a div instead of body. But all your related angular stuff must reside inside it

– Declare variable in the angular scope. Here it is the HelloWorldApp scope ie the page body. The ng-model directive as already explained above ➀ lets you declare the variable.

– Optionally init the variable with ng-init directive : ng-init=”Hello World”.
Note : Usually you would declare variables that are initialized in the controller javascript code (as we will see in the next example) and the variables that don’t need initialization directly in the html with the angular ng-model directive. Here, to keep things simple, I haven’t declared any controller and the variable is initialized directly in the html source with the value “Hello World”.

– Display the variable or its properties as already explained above ➀ with “{{ }}” syntax

Angular JS Controllers and Filters

Angular filters are made to change model element to display on the fly just before displaying it.
It can be a simple format conversions or some criteria to display only part of the elements of an array and you can even create your own filters.

But in order to show you some filter example I am gonna need to use a controller, so let me introduce Angular JS controller first.

Angular JS Controllers

In MVC The controller is the central piece that takes care of interactions between the model and the view.
As we have just seen in the first example some of this is already accomplished by Angular scope and data binding system.

But you can do your custom stuff on top of the scope and to do that you have to define an angular controller in your javascript file :

angular.module('app',[]).controller('myController', function(){/*do some controller stuff here*/});

If you are not used to inline function expressions in javascript, you can do that in several step:

var app = angular.module('app',[]);
function myController(){
  /*do some controller stuff here*/
}
app.controller('myController', myController);

In the html file, you then have to declare that your block will be using your controller

<div ng-controller="myController">...</div>

For example if we wanna display a scope variable declared in the controller
Script:

var app = angular.module('app',[]);
//The $scope parameter is injected by DI thanks to angular
function myController($scope){
  $scope.myvar = "Hello again";
}
app.controller('myController', myController);
<body ng-app="app">
  <div ng-controller="myController">
    myvar is {{myvar}}
  </div>
</body>

Angular JS Filters

Now that we’ve seen controllers, I can show you how to filter data from the controller scope.
The syntax is
For html

{{somethingToDisplay | filter : parameterObject }}

For Js

$filter('filter')(somethingToDisplay, parameterObject)

– somethingToDisplay : some variable or array in the scope you want to filter and display
– | filter : the pipe character followed by a filter name which is the filter to apply to somethingToDisplay before displaying it
– : paramterObject : optional object that you pass to the filter as a parameter
– $filter : Angular object containing all the registered filters.
You can pass $filter to your controller definition by Dependency Injection just adding it in your controller function parameters :

 function myController($scope, $filter)

There are angular predefined filters (core filters) like date, orderBy uppercase and json below. But you can also define your own filters with or without parameters. Let’s see various examples, here is the code!

Filter Source Code

Filter.html

<!DOCTYPE HTML>
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8">
            <title>Casley Consulting Angular tutorial</title>
                <style>
                table, table td {
                    border: 1px solid grey;
                }

            </style>
            <script src="http://code.angularjs.org/1.3.0-beta.17/angular.min.js"></script>
            <script src="Filter.js"></script>

        </head>
        <body ng-app="FilterApp">
            <div ng-controller="MainCtrl">
                <h1> Date Core filter </h1>
                <p>
                    Today is
                    {{ nowTime | date:'yyyy/dd/MM'}}
                </p>
                <hr/>
                <h1> Various Filters </h1>
                <p>
                    Let's display our array as a json object thanks to angular json filter :<br/>
                    {{ employees | json}}
                </p>
                <p>   Let's try other various filters on the array or its items :</p>
                <table>
                    <tr><th>Filter</th><th>Syntax</th><th>Filtered result</th></tr>
                    <tr><td>No filter</td><td></td>
                        <td><ul>
                                <li ng-repeat="employee in employees">
                                {{ employee.name }} : {{ employee.department }}</li>
                            </ul>
                        </td>
                    </tr>
                    <tr><td>Lower case core filter</td><td> employee.name | lowercase </td>
                        <td><ul>
                                <li ng-repeat="employee in employees">
                                {{ employee.name | lowercase }} : {{ employee.department }}</li>
                            </ul>
                        </td>
                    </tr>
                    <tr><td>Upper case custom filter</td><td> employee.name | myUpperCase</td>
                        <td><ul>
                                <li ng-repeat="employee in employees">
                                {{ employee.name | myUpperCase }} : {{ employee.department }}</li>
                            </ul>
                        </td>
                    </tr>
                    <tr><td>Sort by department core filter</td><td>employee in employees | orderBy:'department'</td>
                        <td><ul>
                                <li ng-repeat="employee in employees | orderBy:'department'">
                                {{ employee.name }} : {{ employee.department }}</li>
                            </ul>
                        </td>
                    </tr>
                    <tr><td> Employees whose name contains「Mitsu」 custom filter</td><td>employee in employees | myContains:{field:'name',lookupStr:'Mitsu'}</td>
                        <td><ul>
                                <li ng-repeat="employee in employees | myContains:{field:'name',lookupStr:'Mitsu'}">
                                {{ employee.name }} : {{ employee.department }}</li>
                            </ul>
                        </td>
                    </tr>
                    <tr><td>Combination of filters:<ul><li>Lower case core filter</li><li>Upper case custom filter</li><li> Sort by department core filter</li></ul></td>
                        <td><ul><li>employee in employees | orderBy:'department'</li><li> employee.name | lowercase | myUpperCase </li></ul></td></td>
                        <td><ul>
                                <li ng-repeat="employee in employees | orderBy:'department'">
                                {{ employee.name | lowercase | myUpperCase }} : {{ employee.department }}</li>
                            </ul>
                        </td>
                    </tr>

                </table>

            </div>
        </body>
    </html>

Filter.js

//Declaration of the app module(setter). If we then want to use the getter 「angular.module("FilterApp")」the module must first be set like this
angular.module("FilterApp",[]);

//Controller declaration。The 「$scope」 parameter is passed by Dependency Injection thanks to Angular
function MainCtrl ($scope) {
    //With a new scope variable we expose current time in our scope
    $scope.nowTime = new Date().getTime();

    //Declaration of an array of employees
    $scope.employees = [
        {
            department:"SC",
            name:"Sato"
        },
        {
            department:"SD",
            name:"Suzuki"
        },
        {
            department:"HRS",
            name:"Takahashi"
        },
        {
            department:"Planning",
            name:"Tanaka"
        },
        {
            department:"Business Administration",
            name:"Ito"
        }
    ];
}

// We register a controller in the app module. We can use the module getter thanks to the first line of code of this file.
angular.module("FilterApp").controller("MainCtrl", MainCtrl);

// Definition of a simple custom filter. Make the item parameter uppercase. To implement this behaviour we'll just wrap the existing angular uppercase filter
// $filter is passed by DI. With this object we can use Angular predefined filters or custom ones in the javascript code
function myUpperCase ($filter) {
    return function(item) {
        return $filter('uppercase')(item);
    }
}

// We register the custom filter in the app module
angular.module("FilterApp").filter("myUpperCase", myUpperCase);

// Definition of an array custom filter. For a given array of items, it returns the ones whose filtered property match the requested value. If the property is another value, the item gets filtered out
function myContains ($filter) {
    return function(items, param) {
        return items.filter(function(item) {
            // field: the property targeted by the filter. lookupStr : filtered value. If this value is not in the targetted property, the item is filterd out
            // To do a case insensitive lookup we apply upper case filter on both sides
            return ($filter('uppercase')(item[param.field]).indexOf($filter('uppercase')(param.lookupStr)) > -1 );
        });
    };
}

// We register the custom filter in the app module
angular.module("FilterApp").filter("myContains", myContains);

The code is commented so understanding should be pretty straightforward but here is a few things
– with the directive ng-repeat you can repeat a tag and its content for each employee in the array

<li ng-repeat="employee in employees">{{ employee.name }} : {{ employee.department }}</li>

– You can use core filters in your custom filters : cf myUpperCase
– In this example, be aware some filters applies on the array before it is iterated by ng-repeat and some filters apply on one array element
– If you apply lowercase and myUpperCase the last filter applied wins: the result is upper case

That’s all for today. See you.