angularjs – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Hands on Angular Js-III /hands-on-angular-js-iii/ /hands-on-angular-js-iii/#respond Fri, 25 Mar 2016 09:33:51 +0000 /?p=482 Introduction

Hello folks!! Lets continue our journey of learning Angular JS. We have seen & discussed few topics already!

In this article we will discuss few concepts that are very essential to build an MVC project with Angular.
thinkzooLets see the topics we will be covering in this article:

  • Angular Model
  • Angular Scopes
  • Angular Services
  • Angular Http
  • Angular Dependency Injection

Angular Model

This as the name suggests binds the values to the model associated to an element. This shows a two-way binding, i.e. when the value suppose in the textbox changes, the value for the model also binds and changes. The attribute used is ng-model, the code would be like:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div>Name : <input type="text" />
<h1>Welcome {{name}}</h1>
</div>

This will update the value of text entered inside the text box and gets displayed in real time.
1
Interesting fact about the ng-model directive is that, the directive watches the model by reference not by value. It also provides validation to the particular field.

Angular Scopes

Angular scopes are the execution-context generated during the creation of a controller. We pass the scope object to the controller function. The scope is generally denoted as $scope. This is actually an object to which we add the properties to be accessed in the HTML page using the controller reference.
As the angular doc rightly says, it is actually the glue between the controller and the view. It comes with two referring API i.e. $watch (used to observe the model mutations) and $apply (used to propagate the changes done to the scope object property) Lets have a glance at the snippet:

angular.module('scopeTest', []).controller('TestController', function($scope) {
  $scope.username = Suraj;
 });

This is how the scope object is passed and initialized and assigned properties to be used inside the view.
Interesting Facts:
Controller function in Angular is a constructor function. Now what is a constructor function?
A constructor function in simple terms is when the new keyword is used before a function.

var constructorFunction = new Funciton(Parameters..);

Thus everytime a controller is instantiated it gets associated with a new Scope.

Angular Services

There are many in-built services provided by the Angular and also we can explicitly create our own services to have a loose coupling while using the Http Get Post services. These are actually singleton functions that are required to perform certain specified tasks. What singleton means is restricting the instantiation to a single object only.
As in MVC we follow Separation of concern, here also these services can be used to follow the loose coupling and binding.
2
As we can see here the reuse of the services can also be followed here. This is done using the injection of dependency into the controller function. We will look into the dependency in the next points.
Lets see how we declare a service in Angular.

var module = angular.module('TestApp', []); 
module.service('TestService', function(){
    this.users = ['Suraj', 'CsharpCorner', 'Angular'];
});

Here comes another concept known as Factory, which also behaves as a service function only.

var module = angular.module('TestApp', []); 
module.factory('TestFactory', function(){     
    var testFactory = {};     
    testFactory.users = ['Suraj', 'CsharpCorner', 'Angular'];
    return testFactory; 
});

The behavior is the same for both service and factory, but the difference is interesting. For the difference, take a closer look at the snippets mentioned above. In the first snippet where we have declared the service and we have added the ‘users’ to the reference of the service i.e. this keyword. Whereas, in the .factory declaration, we have used the testFactory object and assigned property users to it. While using the Services in the injection, we will have the object instance of the service becomes the reference to the methods and can be used in the injection for other controllers or services, while in case of factory, when that is injected, the value is directly provided which is returned by the function within.
The above discussed are explicit or user-defined services, now lets see the in-built services provided by the Angular. (Some of them)

  • $http:- This is the Http server requesting service, which is one of the most commonly used and important service.
    var app = angular.module('TestApp', []);
    app.controller('TestCtrl', function($scope, $http) {
        $http.get("url").then(function (response) {
            $scope.testData= response.data;
        });
    });

    As we see in the above snippet, the $http service used to make a get request to the URL specified and then the data retrieved is assigned to the scope. As we see the $http is passed into the controller function as an argument. It is recommended to use the $http, server request inside the service as we are in a way interacting with the data. Then the service is injected into the Controller.
  • $interval:- This as the name suggests, is an angular type for window.setInterval
    var app = angular.module('TestApp', []);
    app.controller('TestCtrl', function($scope, $interval) {
        $scope.theTime = new Date().toLocaleTimeString();
        $interval(function () {
            $scope.theTime = new Date().toLocaleTimeString();
        }, 1000);
    }); //reference for use from https://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_interval
  • $location:- Same as above, angular version of window.location.
  • $timeOut:- Same as above, angular version of window.setTimeOut.

Dependency Injection

This is an interesting and most debated topic and angular provides this out of the box concept.
3 Out of the box.. 😀
Dependency is required when we are looking for the loosely coupled codes, i.e. without directly exposing our services. The separation of concern is the major concern when DI comes into picture. Once our service is ready, we can inject to any other service or controller in Angular. The best example would be a Bakery shop. 😀
Lets chalk out the plan with a simple snippet:

var app = angular.module('BakeryApp', []);
 
app.service('BakeryService', function() {
    //Declare or pass the prices as arg 
    this.Pizza = function(quantity) { return quantity * pizzaPrice };     
    this.Pastries =function(quantity) { return quantity * pastriesPrice };     
    this.Cakes= function(quantity) { return quantity * cakePrice};
});

//Injected Bakery Service to the 'BakeryCalculateService'
app.service('BakeryCalculateService', function(BakeryService){     
    this.PizzaPrice = function(qty) { return BakeryService.Pizza(qty); };
    this.CakePrice= function(qty) { return BakeryService.Cakes(qty); };
 
});

//Injected BakeryCalculateService.
app.controller('BakeryPriceController', function($scope, BakeryCalculateService) { 
    $scope.CalcPizzaRate= function() {
        $scope.PizzaRate = BakeryCalculateService.PizzaPrice ($scope.quantity);
    } 
    $scope.CalcCakeRate= function() {
        $scope.answer = BakeryCalculateService.CakePrice($scope.quantity);
    }
});

We can very well in the above example see the Dependency Injection and the separation of the main service, the layering that is set between the controller and the actual operations. This is very handy during maintenance as well. This is by law which every developer should abide by 😛

Do’s & Dont’s

Another interesting fact when we use the injection is the minification breakage. The angular code breaks when the injection is not done properly when the script files are usually bundled and minified.
The above Dependency Injection snippet we discussed, will break when the script is minified, bundled & deployed. The reason being, when minification takes place, it re-frames the variable names as ‘a’,’b’,’c’.., thus the parameters injected as $scope,$http will be now treated as a, b. Thus this will break as there is no meaning injecting a b, may it be a controller or a service.
To avoid that, we usually modify the snippet and use the Angular attribute $inject, wherever Dependency is injected.

var testController= function(myCtrlScope, $http) {
  //We included $scope and the $http service into our controller.
  }
testController.$inject = ['$scope', '$http']

Since we are using $inject attribute on our controller,it would not be an issue using any name of the parameters to it.

Conclusion

Thus, we have discussed few interesting concepts this time and work around with live snippets. Still we have not discussed the integration of angular with an MVC app using API. We will discuss in the upcoming articles of the series, before that we will be clear on the basic stuffs that needs to be covered. 🙂
I hope this article helps. I am always open for corrections and suggestions.
Lets learn and share together.

]]>
/hands-on-angular-js-iii/feed/ 0
Hands on Angular Js – II /hands-on-angular-js-ii/ /hands-on-angular-js-ii/#respond Sun, 10 Jan 2016 17:51:29 +0000 /?p=462 Introduction

AngLogo
As 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 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 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 withing the modules, along with other dependencies. This is the modular approach in Angular. Creating modules for separate section segregates it and create partition/module wise applications.
The modules are defined syntactically as below:

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:

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>
<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 scopr of the div and Module, we have th right to access the data defined inside the controller function. $scope defined within the controller function is 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 api’s to get post and delete any data through the services. Lets see how the controller function can be separated from the declaration and defined as a function.

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 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 an normal object into JSON format
  • limitTo:- limits an set of array to specified number of elements or objects.
  • lowercase:- converts/formats an 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.

Lets see the work around using the snippets:

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:

<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.

Whats 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

]]>
/hands-on-angular-js-ii/feed/ 0