Angular – 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 AngularJs – I /hands-on-angularjs/ /hands-on-angularjs/#respond Mon, 04 Jan 2016 09:17:47 +0000 /?p=445

Introduction

The stand out hero in the market now. AngularJs it is from Google, intensifying the effectiveness of the plain HTML. There has been a constant and roaring buzz in the market on this. We have heard of MVC (Model-View-Controller), MVVM (Model-View-ViewModel) and many more framework. This is simple Javascript framework based on MVW framework.

MVW??

thinkzoo
Ok now what is MVW!! It stands for Model-View-Whatever . Like Salman Khan says, Whatever you want to do man!! Just Do! So Angular says, Add Whatever you want man!! ๐Ÿ˜€
The reason being is, it is actually close to MVC, MVVM and MVP as well. Earlier it had concepts related to MVC, but after the modification and enhancements and addition of the $scope, it came closer to MVVM framework as well. Thus, the framework became MVW.

Before we start hand on Angular, we need to have the resources required by it and start experimenting in a normal text editor like Notepad++ or Sublime Text. So is it time taking hectic!! Not at all, just navigate now to Angular JS Resources Download add the resources and just start. Even better way!! Just add the below CDN resources and just start. ๐Ÿ™‚

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

Some concepts

Now we have seen a lot of resources explaining the concepts thats new and interesting in Angular JS. Lets get a brief over view on each of the important concepts.

Angular Expressions

This is actually how Angular binds data onto the HTML and makes it dynamic in seconds. The syntax is {{ exp }}. Whatever is written in the braces, that data is bound to the HTML element.

<div ng-app="">
My age is: {{ 15 + 10 }}
</div>

Output would be:
My age is: {{ 15 + 10 }} //Actual angular is used here.

This will display My age is 25 in normal HTML as well.
But one thing, please read further, only this will not let you display the evaluated value. ๐Ÿ˜›

Angular directives

These are kinds of attributes added to the HTML elements, thus extending a new range of attributes to the HTML. ng- is the attribute syntax, just like data- attributes. There are flexibility in the directives as well. There are few in-build directives and there are directives we can create explicitly. Few of them are listed below along with a detailed example of their usage. Lets follow:

  • First and foremost directive is ng-app: This is utmost important directive as it starts/initiates the Angular application inside the HTML. If we remove the ng-app directive then the evaluation will fail as the Angular will not initiate.
  • ng-model: This is another important directive which actually makes our HTML dynamic as it stores the data/handles the data for the form or HTML controls which we add n the web pages.
  • ng-init: This is responsible to initiate the data for the model properties, in order to have some values pre-populated.

Let’s have a look at a simple code snippet:

<div ng-app="">
<input type="text" ng-model="firstName">
<input type="text" ng-model="lastName">
<span>{{firstName}} {{lastName}}</span>
</div>

Here the ng-model binds the firstName and the lastName as you type in the text box to give a dynamic feel.
To make the default names appear on the screen on the page load, we can use the ng-init to initiate the data for the model, just like below:

<div ng-app="" ng-init="firstName='Suraj';lastName='Sahoo'">
<input type="text" ng-model="firstName">
<input type="text" ng-model="lastName">
<span>{{firstName}} {{lastName}}</span>
</div>

Angular JS – MVC

Angular JS, as we mentioned above follows MVC architecture in the background. In the above simple snippets as we saw, how the data is bound to the view from the model values and presented on the UI.
AngMVC
Thus when the event is fired the Angular Controller is reponsible to fetch the data from http services using the $http.get(url) which in turn then binds data to the model using the ng-model and then data is dynamically bound to the view/html element. The concept here is similar and we will learn more on this once we follow up with the controllers and modules in Angular.

Conclusion

This was all about the start and simple directives to get your hands on Angular JS. In the succeeding modules and blogs, we will discuss more in details.

Hand on Snippet

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<h2>Welcome To Angular World</h2>
<div ng-app="" class="form-group">
<label>First Name</label><br>
<input type="text" ng-model="firstName" class="form-control"><br>
<label>Last Name</label><br>
<input type="text" ng-model="lastName"><br>
<br>
<span> Your Name is: {{firstName}} {{lastName}}</span>
</div>
</body>
</html>

What’s Next

  • Modular approach: Creating Modules in Angular ng-module
  • Controllers in Angular ng-controller
  • Scope in Angular $scope
  • Server interaction and binding data from APIs in MVC & Http Services $http
]]>
/hands-on-angularjs/feed/ 0