Thursday, December 19, 2013


What are Javascript, AJAX, jQuery, AngularJS, and Node.js?


JavaScript

JavaScript is a programming language designed for use in a web browser. (It’s no longer a “scripting” language, nor does it have anything to do with Oracle’s “Java”, so the name is a bit misleading.)
You can code in JavaScript – it’s a full-featured language which (with one notable exception) runs in a web browser like Chrome, Firefox, or Internet Explorer. It’s usual use is to manipulate a thing called the “Document Object Model”, essentially elements on a webpage.
JavaScript executes on the client side: A website server sends the javascript to a user’s browser, and that browser interprets and runs the code. This happens inside a “sandbox”, which keeps the javascript from touching the internals of the system, which most of the time keeps malicious code from messing up the user’s computer.
A simple JavaScript program is alert("hello world!");, which on an HTML page would probably be put inside a <script> tag to tell the user’s web browser to interpret the following as JavaScript, like: <script> alert("hello world!"); </script>. This code makes a small alert box pop up on the user’s browser. To see this code execute, click here.
So, to recap: JavaScript is a programming language that operates in the browser, inside a security “sandbox”. It allows manipulation of elements on a webpage.

AJAX

AJAX stands for “Asynchronous JavaScript and XML“, and is a way that a webpage can use JavaScript to send and receive data from a server without refreshing a webpage. XML is a kind of markup language – like HTML, which people sometimes use for sending data across the internet. Recently, JSON (“JavaScript Object Notation”) is more popular and can be natively read by JavaScript. I know that’s a lot of 4-letter acronyms, so let’s recap:
AJAX: Asynchronous JavaScript and XML. A system for sending and receiving data from a server without a page refresh. (example below)
XML: eXtensible Markup Language. A language for organizing arbitrary data. Uses lots of angle brackets “<>”. (example)
HTMLHyperText Markup Language. A subset of XML specifically for describing and organizing web pages. (example)
JSONJavaScript Object Notation. A more modern way of packaging data that’s often used with AJAX. Can be natively read by JavaScript. (example)
A sample AJAX call might work like this:
  1. Client requests page from server
  2. Server responds to request and sends page
  3. Client makes AJAX call to the server and requests more data
  4. Server sends that data.
  5. Client updates the page using that data without refreshing.
Facebook, Gmail, and Pinterest are examples of sites that use a lot of AJAX.
The “Asynchronous” part refers to the fact that when the JavaScript makes the AJAX call to the webserver, it continues to work until the response – it doesn’t “block” and stop while the data is being processed server-side.

jQuery

jQuery is a library built in JavaScript to automate and simplify common tasks. There are many libraries like it, but jQuery really took off because of its power and ability to make things work in older browsers. jQuery is used in the browser, alongside “normal” JavaScript. It is mainly used for animation and AJAX, which are difficult to do with vanilla JavaScript, but are just a few lines in jQuery.
jQuery is included in a web page using the <script> tag; for example: <script src="./path/to/jquery.js"></script>. There are also myriad jQuery plugins, which extend the functionality of jQuery in various ways.
A sample jQuery call, which hides a small box when clicked:
Live Example:
<script src="path/to/jquery.js">
<script>
    $("#box").click(function(){$("#box").slideUp()});
</script>

AngularJS

AngularJS is a full frontend MVC framework for JavaScript web applications. It was built at Google and provides a way to quickly build large, single-page web applications. Like jQuery, it is included into a page using the <script> tag, and is itself written in JavaScript. Unlike jQuery, it is meant to be a framework upon which an entire web application is built. It actually includes a minimal version of jQuery by default.
If you’re looking to learn AngularJS, I recommend EggHead’s video tutorials. You’ll need to have a very solid understanding of JavaScript first, since writing any Angular requires a deep understanding of prototyping, scope, and various other JavaScript aspects.
The AngularJS website has a page of example projects built with AngularJS, if you’re so inclined.

Node.js

Remember how I told you that JavaScript ran in the browser, but I mentioned that there was one big exception to that? Node.js is that exception. It’s a command-line tool that runs JavaScript on a machine without needing to run in a browser. It does this by using a version of Chrome’s V8 Engine, which is the JavaScript engine that runs inside Google Chrome.
Before Node.js, developers would have to use different languages for the backend and frontend of their application. For example, PHP, Java, ASP.Net would run on the server, and JavaScript would run in the client browser. Now with Node.js, developers can use JavaScript on the server as well as the client, meaning that developers can focus on learning one language. Whether this is a good thing is still up for debate (nsfw language).

Conclusion

JavaScript is a language written for websites to run in the client’s browser.
AJAX is a way for JavaScript to request data from a browser without refreshing the page or blocking the application.
jQuery is a JavaScript library built to automate and simplify common web tasks like AJAX or animation.
Angular is a hip JavaScript framework which is made for building large, single-page web applications.
Node.js allows JavaScript to be run without a browser, and is commonly used to run web servers.

Tuesday, December 17, 2013

Global variables in AngularJS:

You've got basically 2 options for "global" variables:
$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.
Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.
Using services is a bit more complex, but not that much, here is an example:
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
  return {
      name : 'anonymous'
  };
});
and then in a controller:
function MyCtrl($scope, UserService) {
    $scope.name = UserService.name;
}

Example of AngularJS "global variables" using $rootScope:
Controller 1 sets the global variable:
function MyCtrl1($scope, $rootScope) {
    $rootScope.name = 'anonymous'; 
}
Controller 2 reads the global variable:
function MyCtrl2($scope, $rootScope) {
    $scope.name2 = $rootScope.name; 
}
See http://jsfiddle.net/natefriedman/3XT3F/1/
   http://jsfiddle.net/3XT3F/10/


An introduction to AngularJS
By Steve Ralston | JavaScript, Web Design | Apr 10, 2013:

When I came across AngularJS a couple weeks ago, I was intrigued at first. By the time I had worked through the set of tutorials available on the AngularJS website, I was thrilled to have found this framework.
What is AngularJS? AngularJS is the (relatively) new kid on the coding block. To quote from their website it is “a structural framework for dynamic web apps” which is especially well-suited for building one-page web apps, although it’s certainly not limited to that.
Developed in 2009 by MiÅ¡ko Hevery and Adam Abrons — both Google employees at that time — it is entirely JavaScript and entirely client-side, so anywhere JavaScript can run, AngularJS can run. It’s also small: compressed and minified it’s less than 29 kb. And it’s open source under the MIT license. You can even use the logo, available under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
According to Wikipedia the goal of Angular “is to augment browser-based applications with model–view–controller (MVC) capability” and it does just that, providing a binding/MVC framework. That’s two-way binding, mind you. Delicious. With a structure as simple as {{ my data }}, you bind data to your page. The $scope service detects changes to the model and modifies HTML expressions in the view by way of controllers. Working in the other direction, changes to the view are reflected in the model. This removes the need for the vast majority of data-centric DOM manipulations many of us, myself included, take for granted when working with a library like jQuery.
Angular runs right out of the box with no library dependencies, although it can be extended with the many modules that are available, and of course you can build your own to fit your specific needs. Being pure JavaScript, it also has the benefit of being server-agnostic.
Being accustomed to a powerful library like jQuery, it’s easy to want to mix it in to do things Angular can already do. Recognizing this potential pitfall, the developers have this to say: “If you’re struggling to break the habit, consider removing jQuery from your app. Really. Angular has the $http service and powerful directives that make it almost always unnecessary.” One thing is for sure, if you stick to Angular, the jQuery loops and explicit back-and-forth with the server will be absent from your code, since Angular provides such a succinct and clean method of achieving the same things.

Directives

Angular uses directives to plug its action into the page. Directives, all prefaced with ng-, are placed in html attributes.
Some common directives that come pre-built with Angular are:
ng-app: this is essentially the initial entry point of Angular to the page. It tells Angular where it gets to act. <html ng-app> is all it takes to define a page as an Angular application.
ng-bind: changes the text of an element to the value of an expression.
<span ng:bind=”name”></span> will display the value of ‘name’ inside the span. Any changes to ‘name’ are reflected instantly in the DOM anywhere the variable is used.
ng-controller: specifies the JavaScript class for the given action. Controllers are typically kept in external .js files.
ng-repeat: creates the very clean loop structures in your page.
<ul>
<li ng-repeat="item in items">
{{item.description}}
</li>
</ul>
effortlessly loops through each item in the collection.
I haven’t used them yet myself, but I have read that creating custom directives can be a tricky issue, something that takes some time to wrap your head around. Angular offers a video to help clarify the concept.

Some sample code

As mentioned before, the ng-app directive in the <html> tag sets the stage for Angular to run in the page.
<html lang="en" ng-app>
Add <script src=”your/path/to/angular/angular.js”></script> to the page head to bring in the Angular framework itself.
<script src=”your/path/to/js/controllers.js”></script> points to the external JavaScript file or files that hold the JavaScript classes your Angular app will call. A very simple class, as an example, might be:
function ItemListCtrl ($scope) {
 $scope.items = [
 { "description": "coffee pot" },
 { "description": "nerf gun" },
 { "description": "phone" },
 ];
}
Passing ng-controller “ItemListCtrl”, the name of my imaginary JavaScript class, tells Angular what code to run:
<body ng-controller="ItemListCtrl">
and double-bracket notation tells Angular what expressions to evaluate.
ng-repeat is a wonderfully succinct repeater directive that loops through the current collection and does the specified action or provides the specified data. It is so simple and clean.
<p>Stuff on my desk:</p>
<ul>
<li ng-repeat="item in items">
{{item.description}}
</li>
</ul>
This simple set up will display:
Stuff on my desk:
coffee pot
nerf gun
phone
Admittedly, that doesn’t seem so impressive, but the idea itself is. Very simple page markup and controllers make getting started with Angular, well, very simple.
Getting real data into your app is pleasingly simple too. Angular likes to consume JSON:
function ItemListCtrl ($scope, $http) {
 $http.get(‘items/list.json').success(function (data) {
 $scope.items = data;
 }
}
This returns a JSON object that can manipulated at will in your Angular app.

And it’s built for testing, too!

One of the basic tenets Angular was founded on was that apps built with it be fully testable. For end-to-end testing we have Angular Scenario Runner to simulate user interactions with your app. You feed it scenario tests written in JavaScript.
For debugging in the browser, AngularJS Batarang is a Chrome extension available on github.

Monday, December 16, 2013

List of angularjs links:

http://www.freeresponsivedesign.com/a-step-by-step-guide-to-your-first-angularjs-app/#more-316

http://net.tutsplus.com/tutorials/javascript-ajax/building-a-web-app-from-scratch-in-angularjs/

http://labs.steren.fr/2013/09/25/angularjs-portfolio-website/

http://kaspars.net/blog/web-development/instagram-slideshow-angularjs

http://davidsalter.com/2013/08/16/using-angular-dot-js-factories-to-get-remote-data/

http://www.sandfield.co.nz/News/Thats-Technical/257/AngularJS

http://blog.harrywolff.com/what-is-angularjs-and-why-is-it-awesome/

http://argutech.blogspot.in/2013/10/simple-angularjs-tutorial.html 

http://pterkildsen.com/2012/11/16/angularjs-tips-and-tricks/

http://www.artandlogic.com/blog/2013/03/angularjs-for-jquery-developers/

http://tom-jaeschke.blogspot.in/2013/12/drop-rows-out-of-html-table-in_16.html

http://www.meetup.com/Austin-All-Girl-Hack-Night/events/122405402/

http://amitgharat.wordpress.com/tag/angularjs/

http://blog.jdriven.com/2013/03/how-to-create-singleton-angularjs-services-in-4-different-ways/

http://www.blogeek.com.ar/2013/05/01/sharing-data-state-on-angularjs-alternatives-comparison-and-my-solution/

http://ngmodules.org/modules/restangular

http://www.slideshare.net/sbegaudeau/angular-js-101-everything-you-need-to-know-to-get-started

http://www.revillwebdesign.com/angularjs-tutorial/

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

http://benpowell.org/useful-angularjs-resources-for-beginners/

http://miceplans.net/?q=node/36

http://vxtindia.com/blog/8-tips-for-angular-js-beginners/

http://toddmotto.com/ultimate-guide-to-learning-angular-js-in-one-day/

http://thesmithfam.org/blog/2012/12/02/angularjs-is-too-humble-to-say-youre-doing-it-wrong/

http://ify.io/lazy-loading-in-angularjs/

http://blog.altoros.com/evaluation-of-angularjs.html

http://tomaszdziurko.pl/tag/angularjs/

http://lhorie.blogspot.in/2013/09/things-that-suck-in-angularjs.html

http://blog.tomaka17.com/2012/12/random-tricks-when-using-angularjs/

http://codetunes.com/2013/little-known-angular-directives/

http://blog.scalyr.com/2013/10/31/angularjs-1200ms-to-35ms/

http://www.peterbe.com/plog/what-stumped-me-about-angularjs



Angularjs inline editing using directive:

<!doctype html>
<html ng-app="">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
    <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.7.0.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
<style>
body {
    font-family: "HelveticNeue", sans-serif;
    font-size: 14px;
    padding: 20px;
}

h2 {
    color: #999;
    margin-top: 0;
}

.field {
    margin-bottom: 1em;
}

.click-to-edit {
    display: inline-block;
}
</style>
  </head>
  <body>

<div ng-controller="LocationFormCtrl">
    <h2>Editors</h2>
    <div class="field">
        <strong>State:</strong>
        <div click-to-edit="location.state"></div>
    </div>
    <div class="field">
        <strong>City:</strong>
        <div click-to-edit="location.city"></div>
    </div>
    <div class="field">
        <strong>Neighbourhood:</strong>
        <div click-to-edit="location.neighbourhood"></div>
    </div>
    <h2>Values</h2>
    <p><strong>State:</strong> {{location.state}}</p>
    <p><strong>City:</strong> {{location.city}}</p>
    <p><strong>Neighbourhood:</strong> {{location.neighbourhood}}</p>
</div>



<script>

app = angular.module("formDemo", []);

app.directive("clickToEdit", function() {
    var editorTemplate = '<div class="click-to-edit">' +
        '<div ng-hide="view.editorEnabled">' +
            '{{value}} ' +
            '<a ng-click="enableEditor()">Edit</a>' +
        '</div>' +
        '<div ng-show="view.editorEnabled">' +
            '<input ng-model="view.editableValue">' +
            '<a href="#" ng-click="save()">Save</a>' +
            ' or ' +
            '<a ng-click="disableEditor()">cancel</a>.' +
        '</div>' +
    '</div>';

    return {
        restrict: "A",
        replace: true,
        template: editorTemplate,
        scope: {
            value: "=clickToEdit",
        },
        controller: function($scope) {
            $scope.view = {
                editableValue: $scope.value,
                editorEnabled: false
            };

            $scope.enableEditor = function() {
                $scope.view.editorEnabled = true;
                $scope.view.editableValue = $scope.value;
            };

            $scope.disableEditor = function() {
                $scope.view.editorEnabled = false;
            };

            $scope.save = function() {
                $scope.value = $scope.view.editableValue;
                $scope.disableEditor();
            };
        }
    };
});

app.controller("LocationFormCtrl", function($scope) {
    $scope.location = {
        state: "California",
        city: "San Francisco",
        neighbourhood: "Alamo Square"
    };
});

/* another way of calling the ng-app, if we write the code, we no need to specify again in the ng-app="formDemo" simply write ng-app="" */
angular.element(document).ready(function() {
    angular.bootstrap(document, ["formDemo"]);
});

</script>


</body>
</html>
what is angularjs?( data copied from https://www.openshift.com/blogs/day-2-angularjs-getting-my-head-around-angularjs ):

What is AngularJS?

  1. Extending HTML to add dynamic nature so that we can build modern web applications with ease
  2. Use the way you want.
  3. Brings you back to HTML
  4. Declarative Approach
  5. Simplicity
  6. Eliminates DOM manipulation by two way data binding. When ever a model changes view gets updated and vice-versa
  7. You can use it to build Single Page Web applications. There are lot of challenges when you build SPA applications like Routing, Ajax calls, data binding, caching, history, and DOM manipulation.
Main components of AngularJS are
  1. Controller : Code behind the view.
  2. Scope : Contains model data. Glues controller and view.
  3. Module : To define new services or use existing services , directives , filters , and so on. Modules can depend on another modules.
  4. Directive : Allows you to extend HTML by defining your own project specific HTML directives. They teach HTML new tricks.
AngularJS from 30000 feet above
Angular High Level

Why should I care?

For me there are two main reasons why I care about learning AngularJS:
  1. Backed by Google and enjoys a large community of developers
  2. Full Stack framework : This means I don't have to rely on a million other scripts without confidence they will integrate nicely together

Prerequisite

We will use Bower to install AngularJS for our sample application. If you don't already have bower installed then follow my previous blog post to learn about bower.

Installing AngularJS

Create a new directory called bookshop at any convenient location on your file system and the run the following command to install AngularJS and twitter bootstrap:
$ bower install angular
$ bower install bootstrap
This will create a folder called bower_components in the bookshop directory where you will have all the installed components.

Let's Use AngularJS

Now that we have AngularJS installed, lets create a html file called index.html which will be our AngularJS based online bookshop application.
<!doctype html>
<html>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container">
          <h2>Your Online Bookshop</h2>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>
If you open this in your web browser you will see "Your Online Bookshop" being rendered. This is not all that interesting so lets add some AngularJS magic:
<!doctype html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-init="books=['Effective Java','Year without Pants','Confessions of public speaker','JavaScript Good Parts']">
        <h2>Your Online Bookshop</h2>
        <ul class="unstyled">
            <li ng-repeat="book in books">
                {{book}}
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>
In the code shown above there are few notable things :
  1. In our html tag we have defined ng-app. This initialize AngularJS app and tells AngularJS to be active in this portion. So , in our application it is active for the full html document.
  2. The second angular directive that we have used is ng-init. This initializes an array of books array which we can use in our application.
  3. The last interesting part is the ng-repeat directive which is used to iterate over all the elements in a collection. Angular would add li elements for each elements. So, if we open this in web browser we will see four books in a list.
The above was using data in the form of String array but you can store objects as well shown below.
<!doctype html>
<html ng-app>
<head>
        <title>Bookshop - Your Online Bookshop</title>
        <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
        <div class="container" ng-init="books=[{'name': 'Effective Java', 'author':'Joshua Bloch'},{'name': 'Year without Pants', 'author':'Scott Berkun'},{ 'name':'Confessions of public speaker','author':'Scott Berkun'},{'name':'JavaScript Good Parts','author':'Douglas Crockford'}]">
                <h2>Your Online Bookshop</h2>
                <ul class="unstyled">
                        <li ng-repeat="book in books">
                                <span>{{book.name}} written by {{book.author}}</span>
                        </li>
                </ul>
        </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>
In the code shown above, we create an array of books object where each book object has name and author. Finally, we list both the author name and the book name in the list.
Using Filters
Angular provides filters which helps format the data. You can use a filter for formatting dates, currency, lowercase characters, uppercase characters, orderBy, and search based filtering. Below is an example how you can make use filters to uppercase Author name and orderby book name:
<!doctype html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-init="books=[{'name': 'Effective Java', 'author':'Joshua Bloch'},{'name': 'Year without Pants', 'author':'Scott Berkun'},{ 'name':'Confessions of public speaker','author':'Scott Berkun'},{'name':'JavaScript Good Parts','author':'Douglas Crockford'}]">
 
        <h2>Your Online Bookshop</h2>
        <ul class="unstyled">
 
            <li ng-repeat="book in books | orderBy :'name'">
                <span>{{book.name}} written by {{book.author | uppercase}}</span>
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>
As you can see above we used a orderBy filter in the ng-repeat directive and we used an uppercase filter while displaying author name.
To add a search filter add a text box for search input and then use a filter to limit your results as shown below.
<!doctype html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-init="books=[{'name': 'Effective Java', 'author':'Joshua Bloch'},{'name': 'Year without Pants', 'author':'Scott Berkun'},{ 'name':'Confessions of public speaker','author':'Scott Berkun'},{'name':'JavaScript Good Parts','author':'Douglas Crockford'}]">
 
        <h2>Your Online Bookshop</h2>
               <input type="search" ng-model="criteria">
        <ul class="unstyled">
 
            <li ng-repeat="book in books | filter:criteria | orderBy :'name'">
                <span>{{book.name}} written by {{book.author | uppercase}}</span>
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
</body>
</html>
Using Controllers
Controllers are one of the main components of AngularJS. They are the code that will power and provide data to your views. In our example we can move the array test data initialization code to a controller. We will create a new JavaScript file called app.js which will house all our application specific JavaScript code.
function BookCtrl($scope){
        $scope.books = [
                {'name': 'Effective Java', 'author':'Joshua Bloch'},
                {'name': 'Year without Pants', 'author':'Scott Berkun'},
                { 'name':'Confessions of public speaker','author':'Scott Berkun'},
                {'name':'JavaScript Good Parts','author':'Douglas Crockford'}
        ]
}
The $scope is the glue between the controller and view and will get injected into our BookCtrl. Now we add our books array to the $scope object which will be visible to our view.
And we will change our index.html to use BookCtrl as shown below:
<!DOCTYPE html>
<html ng-app>
<head>
    <title>Bookshop - Your Online Bookshop</title>
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
 
    <div class="container" ng-controller="BookCtrl">
        <h2>Your Online Bookshop</h2>
        <input type="search" ng-model="criteria">
        <ul class="unstyled">
            <li ng-repeat="book in books | filter:criteria | orderBy :'name'">
                <span>{{book.name}} written by {{book.author | uppercase}}</span>
            </li>
        </ul>
    </div>
 
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Thats it for today's blog. I have only touched tip of iceberg. I will spending many days learning features of AngularJS. It is an amazing and powerful library.