A Better Way to Learn AngularJS

Leave a comment

Source: https://thinkster.io/a-better-way-to-learn-angularjs/

Introduction

Congratulations on taking the plunge!

This AngularJS course is built with the intent of exposing you to the best available resources on each Angular topic. Our desire is to present these topics richly, and from a variety of vantage points, in order to afford you a more complete perspective on them.

The learning curve of AngularJS can be described as a hockey stick. Getting started with apps featuring basic functionality is delightfully easy. However, building more complex apps often require understanding Angular’s inner workings. Failure to do so will cause development to become awkward and cumbersome.

With AngularJS, the “Ready, Fire, Aim” learning methodology of duct taping together a handful of tutorials and a cursory glance through the documentation will lead to confusion and frustration. This curriculum is designed to properly guide you through each of the key Angular concepts thoroughly with a broad exposure to high quality content. With your eventual mastery of AngularJS, you will be able to fluently and efficiently construct large-scale applications.

Prerequisites

Resources

Since AngularJS is still in its infancy relative to other JavaScript frameworks, the number of encyclopaedic resources on it is still insufficient. Therefore, the curriculum will employ a healthy number of excellent blogs in order to offer a more meaty perspective on respective topics.

Kicking the Tires

AngularJS is not a library.

Rather, it is a JavaScript framework that embraces extending HTML into a more expressive and readable format. It allows you to decorate your HTML with special markup that synchronizes with your JavaScript leaving you to write your application logic instead of manually updating views. Whether you’re looking to augment existing JavaScript applications or harness the full power of the framework to create rich and interactive SPA’s, Angular can help you write cleaner and more efficient code.

When descending upon an entirely new topic, it is important to frame the topic correctly before diving into the minutia.

Read the following two entries in the AngularJS guide docs, they will give you a good idea of what you’re about to get into. Don’t worry about picking up on every aspect of the topics they glaze over, all of these will be covered thoroughly in subsequent lessons.

These resources go over a handful of topics that might be helpful in building the appropriate mental models while consuming the Angular curriculum. Some, probably most, of the terms will bounce right off you until you have gone through that section of the course, but it should provide valuable context when approaching a new topic.

Taking It for a Spin

One of the awesome things about AngularJS is its usability right out of the box. Very little information about how the framework operates is needed to get up and running with your first application.

Read the following AngularJS guides followed by lessons that we made to better expose each concept:

Binding

Controllers

Read the AngularJS guide on controllers.

Services

Read the AngularJS guide on services.

Additional Resources

The following set of guides will serve to reinforce many of the topics just covered, and explain some new ones in detail:

Promises

Promises are an immensely important part of the AngularJS framework and with the new ES6 spec, their set to play an important rule in JavaScript as a whole.

Until native promises find they’re way into the browser, Angular uses a stripped down version of the Q promise library called $q.

AngularJS Documentation

Filters

Filters are a simple but powerful tool in Angular, used primarily to format expressions in bindings in views and templates.

Creating a filter

As shown in the video above, creating a filter to manipulate the output of an Angular expression is quite simple. Just by adding the filter name (in this case we’re creating a filter called capitalize) after the pipe | lets Angular know it needs to execute the respective filter on this expression.

<input type="text" ng-model="test.myString" />
<h2>
  {{ test.myString | capitalize }}
</h2>

In order for this to work, we need to create a filter called ‘capitalize’ that will take the string returned from the Angular expression and capitalize all of the letters in it. Adding filters to your Angular application is done by invoking the filter method on angular.module like so: angular.module('app', []).filter('filterName', filterFunction);

Your filter function needs to return a function that will be executed every time Angular needs to evaluate that expression (if the model changes, etc). That function then needs to return the final string output:

function TestCtrl() {
  // basic controller where we preset the scope myString variable
  var self = this;
  self.myString = "hello world";
}

// this is where the filter magic happens.
function CapitalizeFilter() {
  // this is the function that Angular will execute when the expression is evaluated
  return function (text) {
    // text is the original string output of the Angular expression
    return text.toUpperCase();
    // and we simply return the text in upper case!
  }
}

angular.module('app', [])
.controller('TestCtrl', TestCtrl)
// define a filter called 'capitalize' that will invoke the CapitalizeFilter function
.filter('capitalize', CapitalizeFilter);

That’s the general idea of how filters work in AngularJS. However, Angular also ships with some standard filters that you can use out of the box:

Additional Resources

If you’re intered in learning more about writing custom filters, we highly recommend reading this blog post by Todd Motto

Finally, the Angular guides offer a bit more depth on filters:

Directives

Now you’re really getting into the meat of what makes Angular special. Directives are certainly one of the most important facets of the framework, and as such, this is one of the biggest sections of the course.

The general idea behind directives is this: what if you could create your own element and attribute types with corresponding functionality? With directives, you can create custom, reusable components for your application that make developing interactive UI widgets drastically easier. No more custom jQuery code every time you want put a UI widget on the screen; you just place your custom directives there instead!

Creating our first directive

Let’s see what it takes to create our very first directive. We’ll start off by building a simple element called <welcome> that will display a custom message.

To begin building our directive, we will first create an angular module called “greetings” with no dependencies. Then we’ll just call the.directive method on angular.module and create a ‘welcome’ directive. The first parameter will be the name of the directive and the second will be a function for a callback. From this callback, we’ll return an object with a property called “restrict” which will restrict this directive to Elements. The object will also have the property “template” for specifying the HTML for our directive. For our template, we’ll make a div and we’ll say “Howdy there! You look splendid.”

angular.module('greetings', [])
.directive("welcome", function() {
  return {
    restrict: "E",
    template: "
Howdy there! You look splendid.
"
} });

Now that we have a greetings module with a welcome directive which is restricted to “E”, we can jump into our index, create our greetings app, and create our element here, which is the welcome directive.

<body ng-app="greetings">
    <welcome></welcome>
</body>

Once we load the page and check it out, you can see it says, “Howdy there! You look splendid” – and that’s all there really is to writing your very first directive.

We’ll get into the details of what’s going on here in the next few lessons. Basically, as soon as you have an app you can attach directives to that app or module, and in your HTML make sure you define your elements inside of your app.

Building a ‘tab’ Directive

To see a good example of some of these concepts in action, head through our course on building a tab widget:

Advanced Directive Topics

Many of the concepts below are covered in the Tab Directive course but the modules below may help clear up any lingering confusion.

Interestingly, scopes within directives are dramatically underrepresented in mainstream Angular resources compared to how important they are. A solid understanding of scope mechanics is essential when scaling applications, as well as writing modular and testable code. These resources provide good insight on the topic:

Additional Resources

To wrap up, the Angular guides offer a bit more detail on the specifics of some aspects of directives:

The View and the DOM

This section is a bit of a hybrid of seemingly unrelated topics, DOM manipulation, $watch, and view services, but they are closely related, as they all live in close proximity around the application’s views in implementation.

The egghead videos do a superb job of tying these topics together:

Additional Resources

Animations

Animations are a really important part of user interfaces. Fortunately, Angular provides some good tools for making this easy.

Additional Resources

Templates

Despite this being a short section, understanding Angular templates is critical to being able to build applications effectively.

This tutorial is an excellent primer on the subject:

Additional Resources

The documentation guide also has a quick but quality piece on Angular templates:

Routing

Angular routing, while not unduly complicated, does introduce a large number of concepts all at once. It also will handle the lion’s share (or close to it) of logic for many single page applications. It should then be no surprise that this is the largest section of the course.

The following lessons appropriately devote a great deal of podium time to routing:

Additional Resources

Finally, the Angular docs have a great section on the $location service:

$http and Server Interaction

A core requirement of web applications is the need to communicate with other servers. AngularJS allows you to easily do this using the$http service.

In addition to $http, Angular offers a higher level service called $resource, which abstracts away RESTful communication by creating objects that represent routes. The abstraction can often get in the way so $http tends to be the better bet, however $resource can be pretty convenient when communicating with very well defined APIs. If you’re interested, the following tutorial gives a pretty good overview:

Additional Resources

Under the Hood

At this juncture, it’s appropriate to dive into the niceties of AngularJS. In order to truly master the framework, hand-wavy arguments for how things work aren’t sufficient anymore. You need to get into the nitty-gritty of what makes Angular tick.

These egghead videos offer an excellent primer for some increasingly advanced topics:

Additional Resources

Finally, there are a healthy number of Angular documentation guide pages that really get down into dissecting Angular. These are some of the best resources on Angular’s innards out there, make sure and fully take them in:

Development Environment and Testing

Much of Angular’s design is built around being highly testable. Central to this is the widespread utilization of dependency injection, which you read about in Chapter 11. Not only this, but with tools like Yeoman available, a robust test suite becomes realistic and manageable.

There is only one egghead video on testing, and it gives a simplistic overview of a unit test on a filter. (It’s worth mentioning that the Testacular test runner is now called ‘Karma’):

Meet the Gang

A person new to testing might be a little overwhelmed with these concepts and how they play together in the world of testing. This reference should help out:

  • Yeoman has the scaffolding tool yo that generates an application skeleton to start out with, complete with things like Bootstrap or a pre-configured testing setup. The scaffold of the application is different in many ways to the angular-seed scaffold, but it is important to note that they both use Karma and Jasmine in the same ways.
  • angular-seed is a ready-to-eat AngularJS scaffold available on their github with directory structure and testing amenities pre-prepared. Testing this application is accomplished by running a standalone Karma test server.
  • Grunt is the testing tool used in Yeoman, but it is used as a wrapper for Karma.
  • Karma is the actual test runner that is used to test AngularJS. It can be used standalone from Grunt. Karma circumvents testing inconsistencies across browsers, which would happen with things like PhantomJS, by actually launching a browser and running the tests in it.
  • Jasmine is the testing framework which is used for unit tests by default in Karma. Angular E2E tests with Karma don’t and can’t use the Jasmine adapter, although E2E tests use very similar syntax with the Angular Scenario Runner. This blog post does a fine job of going through how to actually author some Jasmine tests, and gives some excellent examples.

Additional Resources

Now that we have fleshed out how testing should generally go, let’s take a look at the Angular docs on testing. These are going to give some more information on how to think about Angular testing. While they are a good resource to have, regrettably, some of them are not yet complete.

More Readings and Examples

Now, read through How to Test an AngularJS Directive. This blog post goes through setting up Yeoman, generating a very simple sample application, writing tests for a directive, and running tests using Karma.
Finally, go through one of the better Angular testing resources to date, Full-Spectrum Testing with AngularJS and Karma. This is an outstanding resource that has fantastic explanations and demonstrations of testing with Grunt and Karma. Included are examples for each of the major testing categories in Angular. It also adds the intermediate Midway test paradigm to the fray, which is a compelling convenience if you’re trying to streamline authoring tests.

Deploying to Production

At Some point you’re going to want to deploy your application to production and code minification is an important part of that process. Unfortunately, the nature of Angular’s DI system can create issues. These issues can be resolved using explicit dependency injection:

Adding and maintaining dependency annotations can be a tedious process. Fortunately there exists and excellent tool for automating this process:

Examples and Analysis

At this point, most of the core Angular topics have been covered, and it’s appropriate to get into some examples. We’ve written a handful of in depth courses that will teach your how to build fully fledged Angular apps:

If you’re interested in building mobile Angular apps, check out our AngularJS + Ionic Tutorial

Additional Resources

Last, we recommend working through the AngularJS documentation tutorial. The format they present it in is a bit too hands-off to be exceedingly helpful, so we recommend playing around with it and modifying it to get the most out of the exercise.

Advertisements

10 Reasons Why You Should Use AngularJS

Leave a comment

Source: http://www.sitepoint.com/10-reasons-use-angularjs/

If you haven’t tried Angular yet, you’re missing out on why people say JavaScript is the most flexible language in the world.

Angular is the only framework that doesn’t make MVC seem like putting lipstick on a pig.

Most frameworks nowadays are simply a bundling of existing tools. They are an integrated tool set, but not very elegant. Angular is the next generation framework where each tool was designed to work with every other tool in an interconnected way.

Here are 10 reasons why you should be using Angular today.

1. MVC done right

Most frameworks implement MVC by asking you to split your app into MVC components, then require you to write code to string them up together again. That’s a lot of work. Angular implements MVC by asking you to split your app into MVC components, then just let Angular do the rest. Angular manages your components for you and also serves as the pipeline that connects them.

Because Angular acts as the mediator, developers also won’t feel tempted to write shortcuts between components that break abstractions just to make them fit easier.

2. A declarative user interface.

Angular uses HTML to define the app’s user interface. HTML is a declarative language which is more intuitive and less convoluted than defining the interface procedurally in JavaScript. HTML is also less brittle to reorganize than an interface written in JavaScript, meaning things are less likely to break. Plus you can bring in many more UI developers when the view is written in HTML.

HTML is also used to determine the execution of the app. Special attributes in the HTML determine which controllers to use for each element. These attributes determine “what” gets loaded, but not “how”. This declarative approach greatly simplifies app development in a sort of WYSIWYG (what you see is what you get) way. Rather than spending time on how the program flows and what should get loaded first, you simply define what you want and Angular will take care of the dependencies.

3. Data models are POJO

Data models in Angular are plain old JavaScript objects (POJO) and don’t require extraneous getter and setter functions. You can add and change properties directly on it and loop over objects and arrays at will. Your code will look much cleaner and more intuitive, the way mother nature intended.

Traditional data models are the gatekeepers of data and are responsible for data persistence and server syncing. Those data models behave like smart data providers. But since Angular’s data models are plain objects, they behave more like a cork board. A cork board is nothing more than a temporary storage area for people to put and retrieve data. However, Angular’s cork boards work closely with a controller and view. To differentiate it from the traditional sense of data models, Angular calls them “scopes”.

All properties found on the scope object are automatically bound to the view by Angular. Meaning, Angular quietly watches for changes to these properties and updates the view automatically.

The scope has no data to begin with and relies on the controller to feed it data according to business logic needs.

4. Behavior with directives

Directives are Angular’s way of bringing additional functionality to HTML. Imagine a world where HTML has so many rich elements (for example <accordion></accordion>,<grid></grid>, <lightbox></lightbox>, etc.) that we never have to manipulate the DOM to simulate them. All that our app needs to do is to assign attributes to elements to get any functionality out of the box.

Directives achieve this by enabling us to invent our own HTML elements. By putting all our DOM manipulation code into directives, we can separate them out of our MVC app. This allows our MVC app to only concern itself with updating the view with new data. How the view subsequently behaves is up to the directives.

Directives come in the form of custom HTML elements

<myticker></myticker>

custom attributes

<div data-myticker></div>

and custom class names

<div class="myticker"></div>

allowing them to be used like regular HTML elements.

Directives are designed to be standalone reusable elements separate from your app. In fact, if a particular element becomes adopted by the HTML5 standard, it should be as simple as removing your custom directive, and your app should behave exactly the same without needing to change your app.

Remember, as a rule of thumb, your controller should not manipulate the DOM directly. All DOM manipulations should be performed by directives.

5. Flexibility with filters

Filters filter the data before they reach the view and can involve something as simple as formatting decimal places on a number, reversing the order of an array, filtering an array based on a parameter, or implementing pagination. Filters are designed to be standalone functions that are separate from your app, similar to Directives, but are only concerned with data transformations.

Filters are so resourceful that it is possible to create a sortable HTML table using only filters without writing any JavaScript.

6. Write less code

All the points up till now mean that you get to write less code. You don’t have to write your own MVC pipeline. The view is defined using HTML, which is more concise. Data models are simpler to write without getters/setters. Data-binding means you don’t have to put data into the view manually. Since directives are separate from app code, they can be written by another team in parallel with minimal integration issues. Filters allow you to manipulate data on the view level without changing your controllers. Yes, this is sort of a summary bullet point, but writing less code is a big deal!

7. DOM manipulations where they belong

Traditionally, the view modifies the DOM to present data and manipulates the DOM (or invokes jQuery) to add behavior. With Angular, DOM manipulation code should be inside directives and not in the view. Angular sees the view as just another HTML page with placeholders for data. This way of looking at the view pairs nicely with user interface designers.

By abstracting out the DOM manipulations and jQuery calls, user interface designers are able to focus on the view without those distractions.

By making your MVC app purely about presenting business data into views, and not have to worry about manipulating DOM, web app development suddenly became more fun.

8. Service providers where they belong

Controllers in Angular are simple functions that have one job only, which is to manipulate the scope. For example, you can use it to prefill data into the scope from the server or implement business logic validations. Unlike other frameworks, controllers are not objects and don’t inherit from anything.

If controllers are so simple, then where should all the heavy lifting be performed? Angular introduces Services to do just that.

Services are exactly what they sound like. They don’t get involved with the MVC of your app, but simply provide an outward API to expose whatever you want it to expose. Most of the time it syncs up to a server to maintain an offline data store and exposes methods to push and pull data to and from a server. Or it can be used to create a resource sharing service that allows multiple controllers to share the same resources.

Services are designed to be standalone objects separate from your app and allow your controller to be remain lean and dedicated to the view and scope that it is assigned to. Of course, implementing services is not required and it is perfectly acceptable to do some light lifting inside your controller to avoid over complexity.

9. Context aware communication

A PubSub system is a pretty common tool that allows for decoupled communication. Most PubSub implementations on the web are not context aware. Sometimes you want a PubSub message to be readable only by children of a particular node, or only readable by the ancestors of a particular child. In other words, sometimes you don’t want unrelated MVC components to be reading your messages.

The PubSub system in Angular is precisely that. broadcast() will send a message to all children controllers, while emit() will send a message to all ancestors.

But PubSub isn’t the only way to communicate between controllers. In fact, if all you’re doing is telling other controllers to update their views when a property changes, you should be relying on data-binding. We already know that the view can be bound to properties on the current scope. But what I didn’t tell you is that scopes inherit the properties of their parent scopes. That means if a property exists on the parent scope, and a child scope modifies it, then all other scopes that inherit from the same parent will also see the same modification and their views will be updated automatically by Angular! This automated way beats using PubSub any day.

10. Unit testing ready

What description of Angular would be complete without talking about it’s unit testing readiness? The whole of Angular is linked together by Dependency Injection (DI). It’s what it uses to manage your controllers and scopes. Because all your controllers depend on DI to pass it information, Angular’s unit tests are able to usurp DI to perform unit testing by injecting mock data into your controller and measuring the output and behavior. In fact, Angular already has a mock HTTP provider to inject fake server responses into controllers.

This beats the more traditional way of testing web apps by creating individual test pages that invoke one component and then interacting with it to see if it works.

These 10 reasons should give you an idea of why Angular is so powerful. Not all web apps should use Angular. For example, if you are writing a game or a computationally intensive math program, there is no reason why Angular would fit your particular problem domain. But for generic web apps, it should serve as a viable framework to build upon.

http://www.angularjs.org/

AngularJS Tutorial – This tutorial is specially designed to help you learn AngularJS as quickly and efficiently as possible. First, you will learn the basics of AngularJS: directives, expressions, filters, modules, and controllers. Then you will learn everything else you need to know about AngularJS: Events, DOM, Forms, Input, Validation, Http, and more. Try it Yourself Examples in Every Chapter

Leave a comment

AngularJS Tutorial

AngularJS is perfect for Single Page Applications (SPAs).

AngularJS is easy to learn.

Learn AngularJS now!

AngularJS extends HTML with new attributes.


This Tutorial

This tutorial is specially designed to help you learn AngularJS as quickly and efficiently as possible.

First, you will learn the basics of AngularJS: directives, expressions, filters, modules, and controllers.

Then you will learn everything else you need to know about AngularJS:

Events, DOM, Forms, Input, Validation, Http, and more.


Try it Yourself Examples in Every Chapter

In every chapter, you can edit the examples online, and click on a button to view the result.

AngularJS Example

<!DOCTYPE html>
<html lang=“en-US”>
<scriptsrc=http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js&#8221;></script>
<body>

<div ng-app=“”>
<p>Name : <input type=“text” ng-model=“name”></p>
<h1>Hello {{name}}</h1>
</div>

</body>
</html>

Try it Yourself »


What You Should Already Know

Before you study AngularJS, you should have a basic understanding of:

  • HTML
  • CSS
  • JavaScript

AngularJS History

AngularJS version 1.0 was released in 2012.

Miško Hevery, a Google employee, started to work with AngularJS in 2009.

The idea turned out very well, and the project is now officially supported by Google.


AngularJS Examples

W3Schools’ AngularJS tutorial contains lots of AngularJS examples!

AngularJS Examples


AngularJS Reference

The AngularJS reference contains all directives and filters used in this tutorial.

AngularJS Reference