Posts Tagged ‘AngularJS’

Why AngularJS ?

Posted: August 9, 2018 in Angular JS
Tags:

AngularJS takes a different stance on how it delivers data-binding and other engineering concepts than frameworks such as Backbone.js and Ember.js. We stick with the HTML we already know and love, letting Angular hijack it and enhances it. Angular keeps the DOM updated with any Model changes, which live in pure JavaScript Objects for data-binding purposes. Once a Model value is updated, Angular updates its Objects which become a source of truth for the application’s state.

  • MVC and MVVM

If you’re used to building static websites, you’re probably familiar with manually creating HTML piece by piece, integrating your “data” and printing the same HTML over and over again. This could be columns for a grid, a navigation structure, a list of links or images and so on. In this instance, you’re used to the pain of manually updating HTML for a template when one little thing changes, you’ve got to update all further uses of the template to keep things consistent. You’ve also got to stamp the same chunk of HTML for each navigation item, for example.

With Angular we have proper separation of concerns, as well as dynamic HTML. This means our data lives in a Model, our HTML lives as a tiny template to be rendered as a View, and we use a Controller to connect the two, driving Model and View value changes. This means a navigation could be dynamically rendered from a single list element, and automatically repeated for each item in the Model.

The difference between MVC and MVVM, is that MVVM is specifically targeted at user interface development. The View consists of the presentation layer, the ViewModel contains the presentation logic and the Model contains our business logic and data. MVVM was designed to make two-way data binding easier, and frameworks such as AngularJS thrive from it.

  • Two way data-binding

Two way data-binding is a very simple concept which provides synchronisation between Model and View layers. Model changes propagate to the View, and View changes are instantly reflected back to the Model. This makes the Model the “single source of truth” for maintaining the applications state.

Angular use plain old JavaScript Objects for synchronising Model and View data-bindings, which makes updating both a breeze. Angular parses back to JSON and communicates best with a REST endpoint. This approach makes building front-end applications seamless as all the application state is held on the browser, not delivered in pieces from a server and state becomes lost.

The way we bind these values is through Angular expressions, which take shape as handlebar templates. We can also bind Models using an attribute called ng-model. Angular uses custom attributes for various APIs that feed back into the Angular core, we’ll learn more about these ng-* prefixed attributes as we continue.

  • Dependency Injection (DI)

Dependency Injection is a software design pattern that deals with how components get hold of their dependencies. An injection is the passing of a dependency to a dependent Object, these dependencies are often referred to as Services.

In AngularJS, we cleverly use the arguments of a function to declare the dependencies we want, and Angular gives them to us. If we forget to pass in a dependency but reference it where we expect it, the Service will be undefined and result in a compile error inside Angular. But don’t worry, Angular throws its own errors and makes them very useful to debug.

  • Application structure

Amongst Angular’s many APIs, we’re given application structure in a consistent fashion, which means generally our applications are all built in a similar way and developers can quickly jump onto projects if necessary. It also creates predictable APIs and expected debugging processes which can enhance development time and rapid prototyping. Angular is structured around “testability” to be as easy to test and develop with as possible.

Advertisements

Intro to Angular JS

Posted: August 8, 2018 in Angular JS
Tags:

Angular is a client-side MVW JavaScript framework for writing compelling web applications. It’s built and maintained by Google and offers a futuristic spin on the web and its upcoming features and standards.

MVW stands for Model-View-Whatever, which gives us flexibility over design patterns when developing applications. We might choose an MVC (Model-View-Controller) or MVVM (Model-View-ViewModel) approach.

AngularJS promotes itself as a framework for enhancing HTML, it brings concepts from various programming languages, both JavaScript and server-side languages and makes HTML the dynamic language too. This means we get a fully data-driven approach to developing applications without needing to refresh Models, update the DOM and other time-consuming tasks such as browser bug fixes and inconsistencies. We focus on the data, and the data takes care of our HTML, leaving us to programming our application.

In this article, we are going to see how to create angular js web application. For that we need the following pre-requisites

  1. npm
  2. git
  3. Visual Studio Code

If you new to my blog, i recommend you read the below older post before your proceed

  1. Intro to AngularJS
  2. Why AngularJS ?

Creating an Angular Starter kit

Well what is a Starter Kit? You see, there are few set of files that a project needs for you to build upon. For instance, you should have angular.js in you project to use the framework. So firstly we will gather all the base files that you can use over and over again every time you start a new project. Reach your favourite work directory and open you terminal there.

Screen Shot 2018-08-06 at 9.25.38 PM

Now execute the npm init command

Screen Shot 2018-08-06 at 9.25.59 PM

Now npm will ask you few questions about your project which you may or may not choose to answer. Lets leave them to default for now.

Screen Shot 2018-08-06 at 9.26.07 PM

You shall see a new package.json file in you directory.

Screen Shot 2018-08-06 at 9.27.42 PM

npm stands for Node Package Manager, which is a huge library of reusable codes that other coders have written and contributed to over the years. So anytime you need something, npm can be used to download it straight into your project. The package.json file you just created keeps track of all the packages you download using npm for your project.

Now in the terminal enter this command

Screen Shot 2018-08-06 at 9.29.08 PM

The npm install is used to install package in your project, that we have not used -g with the code as we want the package to be installed locally in you project and not globally.

The –save is used to update your package.json; it adds the name of your installed package in this file.

Screen Shot 2018-08-06 at 9.29.21 PM

You will notice a new folder named node_modules has appeared in you project. It is where all your node packages reside.

Screen Shot 2018-08-06 at 9.29.33 PM

Import Project to Visual Studio Code

Open Visual Studio. Select File -> Open Folder and choose our project root.

Screen Shot 2018-08-06 at 9.38.57 PM.png

The most important thing about starter kit is to avoid typing the same things over and over again for every new project, so we will now create two files in the root directory – app.js and index.html

Screen Shot 2018-08-06 at 9.42.57 PM.png

Note : The reason we use the –save with our npm command is to edit our package.json automatically. Now if you check the size of the node_module, it is quite huge. You cannot expect to upload it on you github repo. It will consume a lot of space on you repo, and a lot of bandwidth to upload. So what we can do is, tell git to ignore the node_module directory all together. You can see how to do that using “git ignore file”- Google it up. With that said, the next time someone clones you repo on his system, he won’t get any of these node packages and your app will fail to run on his system. Here is where you package.json comes into play. All you would need to do is go into project root and type – npm install and all the required dependencies that were saved using –save will be installed on your friend’s system.

Model View Controller (MVC)

View: This is basically what the user sees. In our case it is the HTML that the browser renders. View takes the data of the model through the controller.

Controller: It is the brain of the app that lets us control the view. It will give us the power to manipulate data and display them in the view. Now in a small scale app, the model is merged with the controller, but as we go big we need to find a way that separates the Model from the Controller, which we will discuss later.

Model: It is the data that the controller can play with. It is used to provide a consistent data for the overall application. In angular, it is usually done using service or factory.

Coming back to our project. Open index.html and paste the following code

So if you know the basics of HTML then you sure know what the above code says. The new thing that I have done is imported the angular.js in our HTML file. This is the heart of the app. This files gives you all the powers of AngularJS in your Web application.

Screen Shot 2018-08-07 at 6.55.02 AM

Now make the following changes. Look for the  comment. Remove them when you are done updating the code. They are just to help you out.

 

Now update app.js with the following code

Screen Shot 2018-08-07 at 6.55.46 AM

Every angular app has a ng-app=” “ attribute. These odd looking attributes are called directives. The name of the web application can be anything you want, but this will be the head of the hierarchy that we will be building now. Lets name it “App” for now ( Its just a convention)

I have also used ng-controller=” “, this is another directive that lets you connect a controller to a specific section of your HTML. Here we have got the whole “body” tag within the scope of the controller. As I have explained before, the controller shall be able to change and manipulate anything that the view displays. So as we have the body scope under our controller here, so anything in the body is within the reach of this controller.

Now in app.js the first line actually creates an angular module. Now understand this, angular apps can be broken down into many modules. This is a way of separating code into different blocks and this gives us the power of plug and play.

Now the “App” is made into a module. This modules uses other modules to function, which become it’s dependencies. So the square bracket there is used to plug in dependencies. The first time you create a module, you have to mention the dependencies of that module. If there are non, leave the bracket blank as I have done for the “main” module.

In this example, I have decided that our “main” module will be the dependency of our “App” module, hence you can see that I have put “main” within the square brackets of “App” module.

You must have noticed that there is no ng-app named “main”, but this is the power of angular. You can now break the app into as many modules you want. So in large scale apps, there can be dozens of modules that depend on another dozens of modules and the tree goes on.

In the last line of the code I have attached the “main” module with the controller we created.Only one module attachment is allowed per controller name. As stated before, out “mainController has the “body” tag under its control, so it is safe to say that the “main” module has direct control over anything that lies in the “body” tag.

The double curly braces in the code tells angular to process whatever we put inside the braces. It can be variables from controller, expressions, strings, etc.

Now lets see how to run the angular application. We need a file server which can be installed from https://www.npmjs.com/package/live-server

Screen Shot 2018-08-06 at 10.03.01 PM

Now let’s start the server by executing the below command : live-server

Screen Shot 2018-08-06 at 10.03.33 PM

Two way data binding

We will use a new directive called ng-model=” “ this time; it is used to bind a scope variable with an input field ( input tags, checkbox, radioButtons etc ). Let’s use an input tag for our purpose and we are binding that to scope variable “msg” and set a default value for it as “Welcome”.

Screen Shot 2018-08-08 at 9.22.16 PM.png

Screen Shot 2018-08-08 at 9.14.09 PM

Remember that the scope variable that is being used in ng-model need not be declared in the controller explicitly. Angular does that internally for you.

Now as you type in something in the input box you shall see the {{msg}} printing out the exact same thing.

At first we were sending data from controller to view, now the view is being modified and this data is being sent to the controller. This is a two way channel that lets the data be changed both from controller as well as the view.

How does it work ?

A very clever trick that is being played by Angular is what we call the Digest Cycle. The digest cycle is not triggered unless it is told to fire up. Many of the out of the box directives implicitly trigger this cycle whenever used. Which means that, directly changing the $scope.msg somehow, will not update the view in real time ( you will definitely come across this situation in future ). What actually happens is that by using the ng-model puts a watcher on the scope variable specified.

Angular maintains a list of all the expressions on which watchers have been placed.

Now whenever the digest cycle is triggered it checks for any change in the value of each expression in the list of all the registered watchers. Ours was placed on variable msg . This way of checking for changes in a list of elements is also refered to as dirty checking. If it finds any change in value since the last digest cycle, it invokes the function specific to the directive that put the watcher in the first place ( ng-model in our case ), after finishing the scan of the last element in list, it goes to the top of the list and starts the scan again to see if the execution of the functions lead to any change in the values of the elements in the list ( and obviously any changes would lead to execution of the respective functions again ), and it does this exactly 10 times! If in the 10th circle, it does not find any change, it safely assumes that everything went well and the changes are reflected in our view, but if in the 10th time it again finds a change then it throws an error realizing that it has got stuck in some kind of infinite update and execute cycle.

Note : You can explicitly use $watcher, $apply() ( best practice as it calls the digest function implicitly ) and $digest() function when the code demands.