ALL >> General >> View Article
Start Working With Angularjs
Start Working With AngularJS
AngularJS is a Javascript MVC framework created by Google to build properly architectured and maintenable web applications.
AngularJS takes another approach. It attempts to minimize the impedance mismatch between document centric HTML and what an application needs by creating new HTML
constructs. AngularJS teaches the browser new syntax through a construct we call directives. Examples include:
Data binding, as in {{}}.
DOM control structures for repeating, showing and hiding DOM fragments.
Support for forms and form validation.
Attaching new behavior to DOM elements, such as DOM event handling.
Grouping of HTML into reusable components.
Why AngularJS?
AngularJS is an MVC framework that defines numerous concepts to properly organize our web application. Our application is defined with modules that can depend from one
to the others. It enhances HTML by attaching directives to your pages with new attributes or tags and expressions in order to define very powerful templates directly in your HTML. It also encapsulates the behavior ...
... of your application in controllers which are instanciated thanks to dependency injection. Thanks to the use of dependency injection, AngularJS helps you structure and test your Javascript code very easily. Finally, utility code can easily be factorized into services that can be injected in your controllers. Now let’s have a closer look at all those features.
Feature 1: Two Way Data-Binding
Think of your model as the single-source-of-truth for your application. Your model is where you go to read or update anything in your application.
Data-binding is probably the coolest and most useful feature in AngularJS. It will save you from writing a considerable amount of boilerplate code. A typical web application may contain up to 80% of its code base, dedicated to traversing, manipulating, and listening to the DOM. Data-binding makes this code disappear,
so we can focus on our application.
Think of your model as the single-source-of-truth for your application. Your model is where you go to read or update anything in your application. The data-binding directives provide a projection of your model to the application view. This projection is seamless, and occurs without any effort from you.
Traditionally, when the model changes, the developer is responsible for manually manipulating the DOM elements and attributes to reflect these changes. This is a two-way street. In one direction, the model changes drive change in DOM elements. In the other, DOM element changes necessitate changes in the model. This is further complicated by user interaction, since the developer is then responsible for interpreting the interactions, merging them into a model, and updating the view. This is a very manual and cumbersome process, which becomes difficult to control, as an application grows in size and complexity.
There must be a better way! AngularJS’ two-way data-binding handles the synchronization between the DOM and the model, and vice versa.
Here is a simple example, which demonstrates how to bind an input value to an
element.
Name:
Enter a name here
Hello, {{yourName}}!
This is extremely simple to set up, and almost magical…
Feature 2: Templates
It’s important to realize that at no point does AngularJS manipulate the template as strings. It’s all the browser DOM.
In AngularJS, a template is just plain-old-HTML. The HTML vocabulary is extended, to contain instructions on how the model should be projected into the view.
The HTML templates are parsed by the browser into the DOM. The DOM then becomes the input to the AngularJS compiler. AngularJS traverses the DOM template for
rendering instructions, which are called directives. Collectively, the directives are responsible for setting up the data-binding for your application view.
It is important to realize that at no point does AngularJS manipulate the template as strings. The input to AngularJS is browser DOM and not an HTML string.
The data-bindings are DOM transformations, not string concatenations or inner HTML changes. Using the DOM as the input, rather than strings, is the biggest differentiation AngularJS has from its sibling frameworks. Using the DOM is what allows you to extend the directive vocabulary and build your own directives, or
even abstract them into reusable components!
One of the greatest advantages to this approach is that it creates a tight workflow between designers and developers. Designers can mark up their HTML as they normally
would, and then developers take the baton and hook in functionality, via bindings with very little effort.
Here is an example where I am using the ng-repeat directive to loop over the images array and populate what is essentially an image template.
function AlbumCtrl($scope) {
scope.images = [
{“thumbnail”:”img/image_01.png”, “description”:”Image 01 description”},
{“thumbnail”:”img/image_02.png”, “description”:”Image 02 description”},
{“thumbnail”:”img/image_03.png”, “description”:”Image 03 description”},
{“thumbnail”:”img/image_04.png”, “description”:”Image 04 description”},
{“thumbnail”:”img/image_05.png”, “description”:”Image 05 description”}
];
}
{{image.description}}
It is also worth mentioning, as a side note, that AngularJS does not force you to learn a new syntax or extract your templates from your
application.
Feature 3: MVC
AngularJS incorporates the basic principles behind the original MVC software design pattern into how it builds client-side web applications.
The MVC or Model-View-Controller pattern means a lot of different things to different people. AngularJS does not implement MVC in the traditional sense, but rather
something closer to MVVM (Model-View-ViewModel).
The Model
The model is simply the data in the application. The model is just plain old JavaScript objects. There is no need to inherit from framework classes, wrap it in proxy objects, or use special getter/setter methods to access it. The fact that we are dealing with vanilla JavaScript is a really nice feature, which cuts down on the
application boilerplate.
The ViewModel
A view model is an object that provides specific data and methods to maintain specific views.
The ViewModel is the $scope object that lives within the AngularJS application. $scope is just a simple JavaScript object with a small API designed to detect and
broadcast changes to its state.
The Controller
The controller is responsible for setting initial state and augmenting $scope with methods to control behavior. It is worth noting that the controller does not store state and does not interact with remote services.
The View
The view is the HTML that exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.
This division creates a solid foundation to architect your application. The $scope has a reference to the data, the controller defines behavior, and the view handles
the layout and handing off interaction to the controller to respond accordingly.
Feature 4: Dependency Injection
AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test.
Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go look for them or make them yourself. Think of it as a way of saying
“Hey I need X’, and the DI is responsible for creating and providing it for you.
To gain access to core AngularJS services, it is simply a matter of adding that service as a parameter; AngularJS will detect that you need that service and provide
an instance for you.
function EditCtrl($scope, $location, $routeParams) {
// Something clever here…
}
You are also able to define your own custom services and make those available for injection as well.
angular.
module(‘MyServiceModule’, []).
factory(‘notify’, [‘$window’, function (win) {
return function (msg) {
win.alert(msg);
};
}]);
function myController(scope, notifyService) {
scope.callNotify = function (msg) {
notifyService(msg);
};
}
myController.$inject = [‘$scope’, ‘notify’];
Feature 5: Directives
Directives are my personal favorite feature of AngularJS. Have you ever wished that your browser would do new tricks for you? Well, now it can! This is one of my favorite parts of AngularJS. It is also probably the most challenging aspect of AngularJS.
Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to “decorate” elements with behavior and manipulate DOM
attributes in interesting ways.
Here is a simple example of a directive that listens for an event and updates its $scope, accordingly.
myModule.directive(‘myComponent’, function(mySharedService) {
return {
restrict: ‘E’,
controller: function($scope, $attrs, mySharedService) {
$scope.$on(‘handleBroadcast’, function() {
$scope.message = ‘Directive: ‘ + mySharedService.message;
});
},
replace: true,
template: ‘
‘
};
});
Then, you can use this custom directive, like so.
Creating your application as a composition of discrete components makes it incredibly easy to add, update or delete functionality as needed.
we will discuss here about how to set up AngularJS library to be used in web application development. We will also briefly study the directory structure and its
contents.
When you open the link https://angularjs.org/, you will see there are two options to download AngularJS library -
AngularJS Download
View on GitHub - Click on this button to go to GitHub and get all of the latest scripts.
Download AngularJS 1 - Or click on this button, a screen as below would be seen -
AngularJS Download
This screen gives various options of using Angular JS as follows -
Downloading and hosting files locally
There are two different options legacy and latest. The names itself are self-descriptive. legacy has version less than 1.2.x and latest has 1.5.x version.
We can also go with the minified, uncompressed or zipped version.
CDN access - You also have access to a CDN. The CDN will give you access around the world to regional data centers that in this case, Google host. This means using CDN moves the responsibility of hosting files from your own servers to a series of external ones. This also offers an advantage that if the visitor to your web page has already downloaded a copy of AngularJS from the same CDN, it won’t have to be re-downloaded.
Try the new angularJS 2 - Click on this button to download Angular JS beta 2 version.This version is very fast, mobile supported and flexible compare to legacy and latest of AngularJS 1
We are using the CDN versions of the library throughout this tutorial.
Example
Now let us write a simple example using AngularJS library. Let us create an HTML file myfirstexample.html as below -
Welcome {{helloTo.title}} to the world of Tutorialspoint!
Following sections describe the above code in detail -
Include AngularJS
We have included the AngularJS JavaScript file in the HTML page so we can use AngularJS -
If you want to update into latest version of Angular JS, use the following script source or else Check the latest version of AngularJS on their official website.Point to AngularJS app Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below -
View
The view is this part -
Welcome {{helloTo.title}} to the world of Tutorialspoint!
ng-controller tells AngularJS what controller to use with this view. helloTo.title tells AngularJS to write the “model” value named helloTo.title to the HTML at this
location.
Controller
The controller part is -
This code registers a controller function named HelloController in the angular module named myapp. We will study more about modules and controllers in their respective chapters. The controller function is registered in angular via the angular.module(…).controller(…) function call.
The $scope parameter passed to the controller function is the model. The controller function adds a helloTo JavaScript object, and in that object it adds a title field.
Execution
Save the above code as myfirstexample.html and open it in any browser. You will see an output as below -
Welcome, AngularJS to the world of Tutorialspoint!
When the page is loaded in the browser, following things happen -
HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded, the angular global object is created. Next, JavaScript
which registers controller functions is executed.
Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function.
Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page is now ready.
Add Comment
General Articles
1. Understanding The Complexity Of The Game Ragdoll HitAuthor: Dana Lynch
2. Unlocking Microsoft's Top-tier Partnership: A Strategic Guide To Azure Partnership Management
Author: Caitlin Parker
3. Documents Needed For Udyam Registration: Annexure Certificate
Author: shweta sahu
4. How To Choose The Right Cappuccino Coffee Machine: A Complete Guide
Author: Ashish
5. Modern Manufacturing Processes
Author: Anthea Johnson
6. How Applying Via Email Lead To Inefficient Job Application Processing?
Author: Indu kumari
7. One Day Picnic Spot In Pune
Author: PUNO Advance
8. Experience Of Rann Utsav Online 2024-25: A Virtual Journey To The White Desert
Author: Rann Utsav Online
9. Comprehensive Legal Solutions In Kazakhstan: Litigation, It Regulations, Labour Disputes, And Competition Law - Almaty Consulting
Author: Prince
10. Disinfectants: Your Germ-busting Superheroes
Author: Vikki kumar
11. Unsecured Business Loan: Fuel Your Business Growth With Sanchetna Finance Pvt. Ltd
Author: Sanchetna
12. Best Laparoscopic Surgeon In Lucknow: Dr. Bhumika Bansal
Author: Dr Bhumika Bansal
13. How To Train Your Sales Team For Lead Conversion Success
Author: Leadzen
14. Mesh Fencing Dubai | Durable & Cost-effective Solutions
Author: Al Mandoos Groups
15. How To Use Vetro Power Shoe Protector Spray Effectively
Author: Vetro Power