A First Step With AngularJS: Part 2

In my previous article A first step with angular js I tried to connect you with AngularJS. I hope I was able to explain the basics of AngularJS.

I have seen many people that believe in picking any complex program and understanding the technology. Somewhere it's a good approach but I am a little bit against this. What I believe and understand is that the technologies with small examples.

We will create small programs, implement a small amount of logic without thinking hard and some profitable output will be the result or not, but one thing is sure; it will give you confidence.

In this article I am trying to move one step ahead with AngularJS by using a few very basic examples.

Let understand the Angular Module

Suppose you are creating an application able to do all the basic mathematical operations add, subtract, multiply and divide. It also has one control able to take numeric input (in Angular we can do this by directives) and a formatting condition by which we can format numeric values as currency (in Angular it's called filters). So we can see that there are many features that exist in a single application. So what name you would like to give this application? I prefer calculator. So if any of your friends come and say I need your calculator application then you will give him the bundle, in other word all 4 methods, directives, filters and so on.

If we look into the Angular context then Calculator is nothing other than an Angular Module. In other words we can say a module as a container for the various parts of your app – controllers, services, filters, directives and so on.

Why Modules?

Most applications have a main method that instantiates and wires together the various 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 need to load relevant modules, that keeps them fast.
  • End-to-end tests can use modules to override configuration.
    1. // declare a module  
    2.   
    3. var myAppModule = angular.module('MyModule', []);  

After declaring the module you can create a controller, filters and directives accordingly.

Have a look at the following example:

  1. <!--ng-app="MyModule" is statement to bootstrapping the module for this program -->  
  2. <html ng-app="MyModule" ng-controller="ControllerForStyle">  
  3. <head>  
  4. </head>  
  5. <body>  
  6.     <div>  
  7.         <input type="number" ng-model="myHeight" />  
  8.         <input type="number" ng-model="myWidth" />  
  9.         <input type="color" ng-model="color" />  
  10.         <! -- set style for div bind with model-->  
  11.         <div style="background-color:{{color}}; height:{{myHeight}}; width:{{mywidth}}">  
  12.             You Entered: {{myHeight}} * {{myWidth}}  
  13.         </div>  
  14.     </div>  
  15.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js">  
  16.   
  17.     </script>  
  18.     <script type="text/javascript">  
  19.   
  20. //Declare module  
  21. var myModule = angular.module('MyModule', []);  
  22. //Create controller with default values of variables  
  23. myModule.controller('ControllerForStyle', function ($scope) {  
  24. $scope.myHeight = 11;  
  25. $scope.myWidth = 20;  
  26. $scope.color='#d33069';  
  27. });  
  28.     </script>  
  29. </body>  
  30. </html>    
There are many other benefits of defining the module, for example by using of a $injector configuration you can manage the big size application.

I believe you are with me so far. Now try to understand the very good feature of angular js is called Filters.

Filters

During the UI design we have all gone through multiple scenarios where we need to show the data with a specific format. So what will you do if you need to show the date in a specific format? Or what will you do if there is a requirement to display the string in Upper Case or Lower Case?

The answer is very straight forward, create a function to pass the value and perform the manipulation then return the formatted/appropriate result. But currently these basic formats are very common and frequently used, so why do we need to implement the methods? Also every time we need to call this method explicitly it is quite complex to implement and understand. Anyways Angular has the answer for this. By using Filters we can achieve this functionality. Angular has multiple built-in filters and we can also create own custom filters as well.

In other words, we can say that Filters will enable you to filter the data before it is projected onto the view. It might involve something straight forward such as date or numbers formatting, or you can implement your own custom filters such as filtering a data source.

And it's very easy to apply a filter on any model value, here is the syntax:

  1. {{ expression | filter }}  

We also can apply multiple filters as in the following:

  1. {{ expression | filter1 | filter2 | ... }}  

Filters may have arguments. The syntax for this is as in the following:

  1. {{ expression | filter:argument1:argument2:... }}  

The following mentioning few of built-in filters (source: https://docs.angularjs.org/api/ng/filter)

Name

Description

filter

Selects a subset of items from array and returns it as a new array.

currency

Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, the default symbol for the current locale is used.

number

Formats a number as text.

date

Formats date to a string based on the requested format.

JSON

Allows you to convert a JavaScript object into JSON string.

lowercase

Converts string to lowercase.

uppercase

Converts string to uppercase.

limitTo

Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array or string, as specified by the value and sign (positive or negative) of limit.

orderBy

Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted correctly, ensure they are actually being saved as numbers and not strings.

So let us create a small program and try to use a few basic filters.

  1. <!--ng-app="MyModule" is statement to bootstrapping the module for this  
  2. program -->  
  3. <html ng-app="MyModule" ng-controller="ControllerForStyle">  
  4. <head>  
  5. </head>  
  6. <body>  
  7.     <div>  
  8.         <h1> Introduction with Angular Filters </h1>  
  9.         Upper Case:  
  10.         <input type="text" ng-model="strUpperCase" />  
  11.         <b>{{strUpperCase |uppercase}}</b>  
  12.         </p>  
  13.         Lower Case:  
  14.         <input type="text" ng-model="strLowerCase" />  
  15.         <b> {{strLowerCase |lowercase}} </b>  
  16.         </p>  
  17.         Number  
  18.         <input type="number" ng-model="varNumber" />  
  19.         <br />  
  20.         <b>  
  21.             Default formatting :{{varNumber |number}}  
  22.             <br>  
  23.             No fractions: {{varNumber | number: 0}} <br>  
  24.             Negative number: {{-varNumber | number: 4}}  
  25.             </p>  
  26.         </b>  
  27.         Currency  
  28.         <input type="number" ng-model="varCurrency" /><br />  
  29.         <b>  
  30.             default currency symbol ($): {{varCurrency | currency}} </span><br>  
  31.             Custom currency identifier (USD$): {{varCurrency | currency:"USD$"}}  
  32.         </b>  
  33.     </div>  
  34.     <scriptsrcscriptsrcscriptsrcscriptsrc ="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js">  
  35.         </script>  
  36.         <script type="text/javascript">  
  37.             //Declare module  
  38.             var myModule = angular.module('MyModule', []);  
  39.             //Create controller with default values of variables  
  40.             myModule.controller('ControllerForStyle', function ($scope) {  
  41.                 $scope.strUpperCase = 'angular is awesome';  
  42.                 $scope.strLowerCase = 'ANGULAR IS AWESOME';  
  43.                 $scope.varNumber = 34.56895;  
  44.                 $scope.varCurrency = 150;  
  45.             });  
  46.         </script>  
  47. </body>  
  48. </html>    

Maybe this example is a little complex to understand all at once but break it into sections and see how the various filters are working. Since we are discussing the filters let us quickly create an example of a custom filter, so you can easily play around with filters and create your own examples to understand filters.

So what I want is that the user will enter a string and our custom filter reverses the string characters and converts it to uppercase if the user wants that.

  1. <!--ng-app="MyModule" is statement to bootstrapping the module for this program -->  
  2. <html ng-app="MyModule" ng-controller="ControllerForStyle">  
  3. <head>  
  4. </head>  
  5. <body>  
  6.     <div>  
  7.         <h1> Introduction with Angular Filters </h1>  
  8.         <input ng-model="varReverse" type="text"><br>  
  9.         No filter: {{varReverse}}<br><br>  
  10.         Reverse: {{varReverse|reverse}}<br><br>  
  11.         Reverse + uppercase: {{varReverse|reverse:true}}<br><br>  
  12.     </div>  
  13.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"> </script>  
  14.     <script type="text/javascript">  
  15.         //Declare module  
  16.         var myModule = angular.module('MyModule', []);  
  17.         //implement a new filter  
  18.         myModule.filter('reverse', function () {  
  19.             return function (input, uppercase) {  
  20.                 inputinputinput = input || '';  
  21.                 var out = "";  
  22.                 for (var i = 0; i < input.length; i++) {  
  23.                     out = input.charAt(i) + out;  
  24.                 }  
  25.                 // conditional based on optional argument  
  26.                 if (uppercase) {  
  27.                     outoutout = out.toUpperCase();  
  28.                 }  
  29.                 return out;  
  30.             }  
  31.         });  
  32.         //Create controller with default values of variables  
  33.         myModule.controller('ControllerForFilter', function ($scope) {  
  34.             $scope.varReverse = 'Great!!! ANGULAR IS AWESOME';  
  35.         });  
  36.     </script>  
  37. </body>  
  38. </html>  

Conclusion

Keep learning, Keep sharing.

Happy Coding.


Similar Articles