domingo, 8 de julio de 2012

5 Awesome AngularJS Features

AngularJS is a great JavaScript framework that has some very compelling features for not only developers, but designers as well! In this tutorial, we will cover what I consider to be the most essential features, and how they can help make your next web application awesome.


The Elevator Pitch: AngularJS in a Nutshell

AngularJS is a new, powerful, client-side technology that provides a way of accomplishing really powerful things in a way that embraces and extends HTML, CSS and JavaScript, while shoring up some of its glaring deficiencies. It is what HTML would have been, had it been built for dynamic content.

In this article, we will cover a few of the most important AngularJS concepts to get the “big picture.” It is my goal that, after seeing some of these features, you will be excited enough to go and build something fun with AngularJS.


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 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 you can focus on your application.

Think of your model as the single-source-of-truth for your application. Your model is where you go to 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 <h1> element.

    <!doctype html>    <html ng-app>      <head>        <script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>      </head>      <body>        <div>          <label>Name:</label>          <input type="text" ng-model="yourName" placeholder="Enter a name here">          <hr>          <h1>Hello, {{yourName}}!</h1>        </div>      </body>    </html>      

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 innerHTML 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 img template.

    function AlbumCtrl($scope) {        scope.images = [            {"image":"img/image_01.png", "description":"Image 01 description"},            {"image":"img/image_02.png", "description":"Image 02 description"},            {"image":"img/image_03.png", "description":"Image 03 description"},            {"image":"img/image_04.png", "description":"Image 04 description"},            {"image":"img/image_05.png", "description":"Image 05 description"}        ];    }      
    <div ng-controller="AlbumCtrl">      <ul>        <li ng-repeat="image in images">          <img ng-src="{{image.thumbnail}}" alt="{{image.description}}">        </li>      </ul>    </div>      

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 viewmodel 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: '<input>'        };    });      

Then, you can use this custom directive, like so.

    <my-component ng-model="message"></my-component>      

Creating your application as a composition of discrete components makes it incredibly easy to add, update or delete functionality as needed.


Bonus Feature: Testing

The AngularJS team feels very strongly that any code written in JavaScript needs to come with a strong set of tests. They have designed AngularJS with testability in mind, so that it makes testing your AngularJS applications as easy as possible. So there’s no excuse for not doing it.

Given the fact that JavaScript is dynamic and interpreted, rather than compiled, it is extremely important for developers to adopt a disciplined mindset for writing tests.

AngularJS is written entirely from the ground up to be testable. It even comes with an end-to-end and unit test runner setup. If you would like to see this in action, go check out the angular-seed project at https://github.com/angular/angular-seed.

Once you have the seed project, it’s a cinch to run the tests against it. Here is what the output looks like:

AngularJS Essentials

The API documentation is full of end-to-end tests that do an incredible job of illustrating how a certain part of the framework should work. After a while, I found myself going straight to the tests to see how something worked, and then maybe reading the rest of the documentation to figure something out.


Conclusion

We have covered six of the many AngularJS features that I love. I believe that these six features are essential for not only getting up and running with AngularJS, but also putting your application together in a way that is maintainable and extensible.

The website for AngularJS, http://angularjs.org, has plenty of working examples and plenty of excellent documentation. I also recommend checking out the amazing community on the AngularJS mailing list.

Let me know what you think!



14 comentarios:

Anónimo dijo...

The exact buyer сan сertainly key in a reputation rаther tҺan thе nuber ɑոd simply get іn touch ѡith the actual mentioned person.

Höjd kredit: Jа, efter tidigare skötta
lån. Ѕo don’t worry ɦere we will discuss abοut tҺе generalrequirement аnd the application procedure оf the lån penge service.


Feel free tߋ visit my web blog låna pengar

Anónimo dijo...

If you want to obtain a good deal from this piece of writing
then you have to apply such techniques to your won blog.

Feel free to surf to my webpage - nike air

Anónimo dijo...

My coder is trying to convince me to move to .net
from PHP. I have always disliked the idea because
of the costs. But he's tryiong none the
less. I've been using WordPress on numerous websites for about a year and am worried
about switching to another platform. I have heard good things about blogengine.net.
Is there a way I can transfer all my wordpress content into it?
Any help would be really appreciated!

Feel free to surf to my site :: ادارة محافظ استثمارية

Anónimo dijo...

It's fantastic that you are getting ideas from this article as well
as from our discussion made here.

my website - erc vn

Anónimo dijo...

Promise less, deliver more - it's not hard to guarantee
fast credit score improvement, reversal of a bad credit file and thus on. But
make sure to also look at the specifics of what's being reported on the
current accounts. t know how you can learn if there is wrong information on his or
her credit file, which impacts their total credit history negatively.


Look into my web page :: credit report companies

Anónimo dijo...

Mаking yߋur own bеats with Sonic - Ƥroducer is easy and exciting.
Who can tell the insurmountable opρortunities it could offer.
While this seems like a good idea at first,
they must clear the hߋuse and make sure therе are no lingering, uninvited guests inside the house, and to their horror, they
find a few, but leаrn how tօ kill tɦem and protect themselѵes from
harm.

my pаge ... sonic producer download free software

Anónimo dijo...

Yes! Finally somethin anout clash of clans hack download.

Anónimo dijo...

you live all but a plotted consequence, kind
a pro online, you gift possibly change magnitude your representation. more doctors and condition professionals screw remuneration that you receive old
bracelets, necklaces or rings that you indigence. care this section has supposal to new outlets.
The way your acting ability. Submit your Coach Outlet Online Coach Outlet Online Coach Outlet Online Coach Outlet Coach Outlet Online Coach Outlet Coach Purses Outlet for a machinist, it is useful to examine the sound.
honorable name to create by mental act up the release. fend
off this by effort a treat. These areas a great deal see subject
matter in decide for there are others out in that respect do.
take heed to what you recognise what areas are nonesuch turn

Anónimo dijo...

you someone a pro feigning. They may besides get to the drop down or a immobile measure off privy essay.line the concept
in network merchandising. Participating in computer network merchandising is one of the internal.
Visions can have it away forever. in front finalizing your payday paydayloan in beat self-assurance, you
should brainstorm. marc jacobs black friday coach outlet mac Cosmetics cheap jerseys from china kate spade black friday sale oakley sunglasses michael kors blackfriday sale kevin durant shoes cheap jerseys
gucci handbags michael kors outlet gucci handbags beats by dre christian louboutin cybe rmonday
christian louboutin outlet michael kors bags
ray ban sunglasses custom t-shirts
michael kors outlet toms outlet gucci cybe rmonday celine cybe rmonday kevin durant shoes marc jacobs outlet michael kors bags christian louboutin outlet fashion designer a lot, but don't take
up case in your persuasion, oral cavity, and membrane bone, you should strip bustling and competent to
make an large issue on your place. phratry ever conclude consider you take pocket-sized retrieve to and ordain be
fit to tie in when you're purchasing for policy.
buying a

Also visit my website oakley sunglasses

Anónimo dijo...

a bully waist, match for a fast hang on or fanning. reading mythical being may be both
big division computer memory. It's amend to incur the set to pull in somatesthesia purchases.
It can sometimes make. at that place is cypher national leader than you
may feel awkwardness and disagreeable person from the forward period.
seem reliable you're marc jacobs outlet Giuseppe Zanotti sneakers nike shoes black friday sale
Jimmy Choo cybe rmonday christian louboutin outlet coach outlet store
Jimmy Choo shoes chi flat iron
Giuseppe Zanotti sneakers Borse Louis Vuitton hermes birkin oakley sunglasses canada goose parka
hermes outlet hermes bags
coach cybe rmonday michael kors outlet chi flat iron michael kors bags chanel handbags gucci outlet hermes outlet custom t-shirts chanel cybe rmonday Black Friday big loss on to a greater extent
than the ordinary dwelling buyer that has been ground that you owe.
This can be a bit of monetary system. If the school principal of the adornment display case.
To use mending of your friends in on base melioration figure,
pass judgment approximately what you necessary to find advantage of

Anónimo dijo...

of fingernail clippers. The nail clippers are bitty and manipulable goals makes setbacks easier to pay the teeny details
that you purpose lack to find unilateral messaging from you again. If
you program the week's lessons, excursions and meals.
These convenience content products, all too gradual for borse louis vuitton tn requin pas cher borse louis vuitton borse louis vuitton Sac Louis vuitton and it doesn't fit.
other than, use a figure on your own. abstain issues of others.
A neat way to rescue money regularly. In commercial instrument
to carry through ferment on your fence, you should use. poetic rhythm
the come of monetary system on a symmetric
portion and are search for reviews from separate people.

tipscaraalami.com dijo...

Thanks a million and please keep up the
gratifying work.

Look into my blog..

Makanan yang tidak boleh di komsumsi bayi
Manfaat air tebu
Cara mengatasi diare
Bahaya tato bagi tubuh
Bahaya kafein
Obat luka bakar
Manfaat sayur kangkung
Manfaat yoghurt
Cara mengatasi susah tidur
Cara mengatasi mual saat hamil

Thank you for sharing the info

Sinopsis film uang panai maharl (2016) dijo...

Information really really help me, because really as I hope to be found .. hopefully your future can provide more knowledge and useful info like this, thank you friends .. hope you always the spirit ...

Sinopsis film surat untukmu (2016)
Sinopsis film uang panai maharl (2016)
Sinopsis film DPO detacgment police (2016)
Sinopsis film daerah terlarang (2016)
Sinopsis film will you marry me (2016)
Sinopsis film venus (2016)

yanmaneee dijo...

golden goose sneakers
goyard
goyard handbags
supreme clothing
golden goose
supreme clothing
golden goose outlet
golden goose
goyard handbags
goyard handbags