What is AngularJS?
Basically AngularJS is an opensource javascript framework, created and maintained by Google which is used in Single Page Application (SPA) projects. What AngularJS does is, it extends the HTML DOM with additional attributes to make it more responsive to user interactions. It is based on the MVC or the Model-View-Controller architecture.
What is MVC?
MVC or Model-View-Controller architecture is a popular design pattern for developing web applications and is made up of three parts. As the name states:
- Controller – responsible for the interactions between the model and the view.
- View – displays the data
- Model – manages the data
MVC supports separation of concerns which means that the logic is hidden from the view. The controller gets requests from the view, takes them to the model, the model handles the required processes and then the output is taken back to the view along the controller.
Writing your first AngularJS application
Lets create a simple application where you have to enter your name within a textbox and it is being displayed in the same page realtime. AngularJS directives are used to extend the functionality of HTML tags. They are special attributes used within html tags starting with the 'ng-' prefix.
We use 'ng-app' directive to define the AngularJS application. This could be anywhere within the html file. But all the functionality will be limited to the scope you define. Basically, ng-app defines the start of the application.
An input tag is used to define the textbox we need to get the user input. The 'ng-model' directive is used to bind the values of AngularJS application data to html inputs:
<input type="text" ng-model="name">
Now what we need is a place to display the value entered in the textbox. We use the 'ng-bind' directive to bind the data in the application model to html tags:
<p>Hello <span ng-bind="name"></span>!</p>
Interpolation
We denote interpolation using double curly braces {{}}. Basically what happens is, anything within the {{}} is being evaluated by AngularJS. For example {{2+2}} would result in the output of 4. We could use {{}} instead of the span tag from the example before.