Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / AngularJs

Hands on Angular JS – II

4.43/5 (4 votes)
10 Jan 2016CPOL5 min read 4.9K  
Hands on Angular JS – II

This article is an entry in our Microsoft Azure IoT Contest. Articles in this section are not required to be full articles so care should be taken when voting.

Introduction

AngLogo
We discuss in the previous part of Hands on Agular Js-I about the basic and the architecture of the Angular Js and few directives. Here in this part, we will check out the other important directives and how Angular interaction with Controller and model is being done on the go. The directives we will discuss in this part of the series are very important in order to start and feel the magic of Angular. Here, actually, we get into the depth and controls of Angular. Let’s watch out. :)

Angular Directives

Here, we start with the other important directives that would come in handy while working on the Angular.

ng-module

Angular modules are the most important directive, they define an angular application. They are the parent set for the other directives or functions of the application, like controllers. Controllers are always contained within the modules, along with other dependencies. This is the modular approach in Angular. Creating modules for separate section segregates it and creates partition/module wise applications.
The modules are defined syntactically as below:

JavaScript
var app = angular.module("app-Services", []);

As per the above snippet, we have created an angular module and assigned it to the variable named app. The module name is app-Services. The module is actually defined in the document function of a separate Module script file and reference added to the file wherever required. The definition provided by the Angular Doc is that Module is required to configure the $injector and it contains the services, directives, controllers and other dependencies.
$injectors are the service used to retrieve the pre-defined object instances, invoke methods and load the required modules.

ng-controller

This is another set of directives that defines the controller of the application, which controls the data of the application. They are simple objects defined under the scope of the module. There can be any number of controllers for a specific module. Controllers are defined syntactically as:

JavaScript
var app = angular.module('app-Services', []);
app.controller('myFirstController', function($scope) {
    $scope.firstName = "Suraj";
    $scope.lastName = "Sahoo";
});

The above snippet is a simple controller defined under the module app-Services. The name of the controller is myFirstController and under its scope, two members are initialized, that is firstName & lastName. Thus, when an object of controller is created in the html, which we will see below:

HTML
<html>
<body>
<div ng-app="app-Services" ng-controller="myFistController as ctrlFirst">
<span>{{ctrlFirst.firstName}} {{ctrlFirst.lastName}}</span>
</div>
</body>
</html>

Thus, as we see above, the html tag div has the scope for the Module we defined above and the controller defined for the module with the members firstName & lastName. When the controller is instantiated inside the scope of the div and Module, we have the right to access the data defined inside the controller function. $scope defined within the controller function is the context via which the model execution is implemented inside the controller. It actually acts as a watch on the model values while binding to the DOM element in the HTML. The $scope can also be used using the this object. The controller also accepts the $http to execute the http services in order to call the APIs to get post and delete any data through the services. Let's see how the controller function can be separated from the declaration and defined as a function.

JavaScript
var app = angular.module('app-Services', []);
app.controller('myFirstController', myFirstController);
function myFirstController($http, $scope) {
    $scope.firstProperty = 'XYZ';
    $http.get('your url').then(function (){ 
                          //do whatever..
                  }).catch(function (){
                         //do whatever..
              }).finally(function (){
                       //do whatever..
          });
}
});

Now the above, $http is the http module which is used to call the get and post methods or to interact with the server to fetch the records. Call the url, like in Ajax we have success and error methods, here we have, then() block, which after fetching successful response, has the logic what to do next. Actually, the $http returns a promise, so we catch that in the then block and attach the response to the scope. The different $hhtp methods are:

  • $http.get: To retrieve information from server for a url requested by the user
  • $http.head: Transfers only the header and the status line only, but is same as GET
  • $http.post: As self explanatory it is, it is used to send the information entered by user to the server
  • $http.put: This is same as the POST but is used to create the current reprsentation of the target resource or overwrite it for the same URL
  • $http.delete: This ensures that the current resource for the requested URL is deleted by the server.

The catch finally is the same as the try.. catch.. blocks, where inside the catch, we can also have the ‘then’ block in order to perform tasks after catch and similarly the ‘finally’ block to ensure what finally the code block will execute.

Filters in Angular JS

These are very interesting features provided by the Angular, which can be frequently used and with ease. We will discuss below the pre-defined filters provided by the framework. We will see the use syntactically after the line by line explanation.

  • currency: This is used as the name suggests, convert a simple number into the format of a currency.
  • date: This is used to format dates in different formats.
  • filter: An interesting filter which actually filters few data from a set of result set data.
  • json: Formats a normal object into JSON format
  • limitTo: Limits a set of array to specified number of elements or objects.
  • lowercase: Converts/formats a string to lower case character.
  • number: Formats a simple number into a string.
  • orderby: Orders an array based on an expression.
  • uppercase: Formats the string into a upper case character.

Let's see the workaround using the snippets:

JavaScript
var app = angular.module('app-Services', []);
app.controller('myFirstController', function($scope) {
    $scope.firstName = "Suraj";
    $scope.lastName = "Sahoo";
});
<html>
<body>
<div ng-app="app-Services" ng-controller="myFistController as ctrlFirst">
<span>{{ctrlFirst.firstName | uppercase}} 
{{ctrlFirst.lastName \ lowercase}}</span> //Displays firstName is UPPERCASE and lastName in lowercase
<ul>
  <li ng-repeat="name in names | orderBy:'age'">
    {{ x.name + ', ' + x.age}}
  </li>
</ul>
<span>{{price | currency}}</span>
<li ng-repeat="name in names | filter : 'S'">
    {{ name }} //Filters names based on names containing 'S'
  </li>
</div>
</body>
</html>

In the above snippets, we have used another directive i.e., ng-repeat, that is used to loop through the list of records just like foreach loop.
Another thing here to note is that the filter used in the above snippet, if we use the object containing the data or list of records/names suppose like:

JavaScript
<p><input type="text" ng-model="nameFilter"></p>
<ul>
  <li ng-repeat="name in names | filter:nameFilter">
    {{ name }}
  </li>
</ul>

What the above snippet does is, it loops through the names and based on the entry in the textbox or the user input, like suppose user enters ‘S’, then the data listed are filtered on the object with the names that Starts With ‘S’.
Thus, we saw how these filters become handy and really useful.

Conclusion

Thus, here in this part, we discussed about most of the great features of Angular and saw a few snippets to be used in progress. As I said earlier, in the succeeding modules, we will gradually come across more interesting features and overall use of Angular.

What's Next??

We will next come across how to build applications using ASP.NET MVC, EF Code First, Angular JS. That I assure would be interesting.

References

  • W3 schools
  • docs.angularjs.org

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)