AngularJS 2.0 : Environment setup

Here are simple steps you need to follow to get Angular Js 2.0 application up and running on your box.

# Make sure you have latest nodejs download link>

# Using npm install type script from command line>  npm install g typescript

# Download latest angular cli too > npm install g angularcli@latest

You are all set up create your new dream app, Angular CLI tool would create the basic structure required for a new app, since you have environment ready, lets create your dream app and run it on cli server

# Run Below commands, it would create you app.

$ng new my-dream-app

$cd my-dream-app

$ng serve



You might want to download atom IDE with supporting package from

Protractor : End-to-end test framework for AngularJS applications

Protractor runs tests against your application running in a real browser, interacting with it as a user would.

The Protractor documentation for users is located in the protractor/docs folder.

To get set up and running quickly:


Splice to add, replace and remove javascript array

Here is working code link :

Splice is an effective way to add, replace or remove elements from specific index in Javascript Array.

Javascript array splice() method changes the content of an array, adding new elements while removing old elements.


Its syntax is as follows −

array.splice(index, howMany, [element1][, ..., elementN]);

Parameter Details

  • index − Index at which to start changing the array.
  • howMany − An integer indicating the number of old array elements to remove. IfhowMany is 0, no elements are removed.
  • element1, …, elementN − The elements to add to the array. If you don’t specify any elements, splice simply removes the elements from the array.

Return Value

Returns the extracted array based on the passed parameters.

If you specify a different number of elements to insert than the number you’re removing, the array will have a different length at the end of the call.


Using splice()

The following script illustrates the use of splice():

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']

AngularJs : Inheritance in Controllers

Here is link of working example :

In order to take advantage of inheritance of scope in Nested controllers, one has to define Controllers one into another using ng-controller attribute. Sometimes you don’t want to define controllers like this but still want to use power of inheritance within controllers. May be you want to put common logic into BaseController and use it in all the child controllers.

In order to achieve this, we must use $injector object that AngularJS provides.

function BMWController($scope, $injector) {

$injector.invoke(CarController, this, {$scope: $scope});

$ = 'BMW';


Link : A nice website to learn AngularJs and Animation :


In this web site concepts are explained in details with working code demo. It is very light weight and funny. If you are stressed by reading high fundu articles, try this simple yet affective website to learn programming and angularJs.

Difference between @, & and = in AngularJs

@ allows a value defined on the directive attribute to be passed to the directive’s isolate scope. The value could be a simple string value (myattr="hello") or it could be an AngularJS interpolated string with embedded expressions (myattr="my_{{helloText}}"). You can think of it as “one-way” communication from the parent scope into the child directive. John Lindquist has a series of short screencasts explaining each of these. Screencast on @ is here:

& allows the directive’s isolate scope to pass values into the parent scope for evaluation in the expression defined in the attribute. Note that the directive attribute is implicitly an expression and does not use double curly brace expression syntax. This one is tougher to explain in text. Screencast on & is here:

= sets up a two-way binding expression between the directive’s isolate scope and the parent scope. Changes in the child scope and propagated to the parent and vice-versa. Think of = as a combination of @ and &. Screencast on = is here:

Using JSONP with AngularJS


AngularJS’s $http service is capable of sending JSONP requests. The normal AJAX calls can only send requests to URLs within the same domain as the HTML page sending the requests was loaded from. You can get around this with JSONP requests.

JSONP is short for “JSON with Padding”  A JSONP request is not sent via the XHR object like AJAX calls normally are. Instead, a <script> element is created and inserted into the HTML page. Here is an example of how such a <script> element could look:

<script src=""></script>

The src attribute contains the URL of the remote service to call with the JSONP call. This URL should include any parameters you need to send to the remote service.

When the <script> element is inserted into the HTML page, the browser will load the script from the given URL. That enables the remote service to send JavaScript back to your application for execution.

The JavaScript returned by the remote service should be a function call to an existing JavaScript function in your HTML page. Here is how the returned JavaScript could look:

theServiceResponse( { name : "John", title : "CEO", company : "BigFatCo" } );

This code makes a function call to the function named theServiceResponse. This function must be present in your HTML page already. Inside this function you process the response sent back from the service.

When the theServiceResponse() function is called, a JavaScript object is passed to the function as parameter. This JavaScript object contains the response parameters from the service call. Thus, this JavaScript object is generated by the remote service. Whatever the remote service wants to send back to you is what this JavaScript object contains. Seen from the remote service’s perspective, that JavaScript object is just JSON like any other JSON sent back to an HTML page. The difference is that this JSON object is wrapped in a function call. This function call is the “padding” part of the “JSON with Padding” name for JSONP.

You might wonder how the remote service knows the name of the function to wrap the returned JSON in. The answer is, that you pass that name to the remote service along with the other request parameters. The function name is one of the request parameters. By default this parameter name is callback but you will have to check with the concrete service to see what parameter name it expects for the function name.

In AngularJS the function name is supplied behind the scene by AngularJS, so you don’t have to worry about adding it to the URL of the remote service.

You use JSONP calls via the $http service like this:

$http.jsonp( url, config );

Like with the AJAX functions the jsonp() function takes a url and a config object. Here is an example of a JSONP call with the url and config objects supplied:

var url =";
var responsePromise = $http.jsonp( url,
             {  params : {
                   p1 : "v1"
                  ,p2 : "v2"

responsePromise.success(function(data) {
    // do something with the returned JavaScript object
    // ( in the "data" parameter ).

This example makes a JSONP call to the service URL Like with the other AJAX functions of the $http service, the config object can contain a params field. This field should be a JavaScript object containing all the request parameters to append to the URL of the remote service.

When you call the $http.jsonp() function AngularJS will create <script> element for you, and insert it into your HTML page. AngularJS will also create the final URL of the remote service by appending the parameters passed in theconfig.params object to the URL.

The URL passed to the $http.jsonp() function must contain the callback=JSON_CALLBACK parameter. AngularJS will replace the JSON-CALLBACK string with the name of a callback function which AngularJS creates.

The promise object returned by the $http.jsonp() function has a success() function, just like the other AJAX function call promise objects. Unfortunately we do not have access to the HTTP headers of the response sent back from the server, since that request is handled by the browser internally, when evaluating the <script src="url">element. That also means that if the JSONP call fails, we have no way of knowing so, since no callback function will get called in that case (no JavaScript to execute from the remote service).

JSONP Security

You have to be careful with JSONP calls. When you make a JSONP call. The remote service could send back anyJavaScript which would then get executed inside your HTML page. An evil remote service could send back JavaScript which attempts to steal information from your application and sent it to a third party service. Only make JSONP calls to services you trust.

How to use Ajax calls in AngularJs

In AngularJS you can send AJAX requests in several different ways. These are:

  • AJAX calls via the $http service.
  • JSONP calls via the $http service.

Note: So far only the $http service is covered (both normal AJAX and JSONP), but that is enough to get you started using AJAX in AngularJS.

The $http Service

The $http service is the easiest way to send AJAX calls to your web server. Remember, that AJAX calls cannot be sent to a different domain than the domain from which the HTML page making the AJAX calls is loaded. For instance, if the HTML page was loaded from then that HTML page can only make AJAX calls back to URLs within the domain.

Here is a full AngularJS application with a single $http AJAX example:

<!DOCTYPE html>
<html lang="en">

    <script src=""></script>

<body ng-app="myapp">

  <div ng-controller="MyController" >
    <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
    Data from server: {{myData.fromServer}}

    angular.module("myapp", [])
        .controller("MyController", function($scope, $http) {
            $scope.myData = {};
            $scope.myData.doClick = function(item, event) {

                var responsePromise = $http.get("/angularjs-examples/
json-test-data.jsp"); responsePromise.success(function(data, status, headers,
config) { $scope.myData.fromServer = data.title; }); responsePromise.error(function(data, status, headers,
config) { alert("AJAX failed!"); }); } } ); </script> </body> </html>

Notice how the controller function registered with the module takes two parameters: A $scope object (as always) and an extra $http object. The $http object (or “service”) is used to make AJAX calls.

The the $http.get() function returns a “promise” object. This promise object has a success() and an error()function. By calling these functions and pass a function to them as parameter you can control what happens when the AJAX call finishes. If the AJAX call succeeds (the server sends back an HTTP code between 200 and 209), the function passed to the success() function is executed. If the AJAX call fails (all other codes except for redirects), the function passed to the error() method is executed. The succss() and error() functions are covered in more detail later.

When to use $apply() in AngularJs

when do you need to call $apply()? Very rarely, actually.

The $apply() function is useful when integrating AngularJS with outside code or non angularJs Javascript code residing in your application. Here we are using a JS function to use event listener so we might have to wrap it with apply to actually get it applied in AngularJs Winking smile Basically apply/digest updates the binding.

document.getElementById("updateTimeButton") .addEventListener('click', function() { $scope.$apply(function() { console.log("update time clicked"); $ = new Date(); }); });

Notice how the $scope.$apply() function is called from inside the button event listener, and how the update of the$ variable is performed inside the function passed as parameter to the $apply() function. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

AngularJS actually calls almost all of your code within an $apply call. Events like ng-click, controller initialization, $http callbacks are all wrapped in $scope.$apply(). So you don’t need to call it yourself, in fact you can’t. Calling $apply inside $apply will throw an error.

You do need to use it if you are going to run code in a new turn. And only if that turn isn’t being created from a method in the AngularJS library. Inside that new turn, you should wrap your code in $scope.$apply().

AngularJS provides wrappers for common native JS async behaviors:

  • Events => ng-click
  • Timeouts => $timeout
  • jQuery.ajax() => $http

This is just a traditional async function with a $scope.$apply() called at the end, to tell AngularJS that an asynchronous event just occurred.

$scope.$apply() should occur as close to the async event binding as possible.

Do NOT randomly sprinkle it throughout your code. If you are doing
if (!$scope.$$phase) $scope.$apply() it’s because you are not high enough in the call stack.

Whenever possible, use AngularJS services instead of native. If you’re creating an AngularJS service (such as for sockets) it should have a $scope.$apply() anywhere it fires a callback.

How to make Ajax calls from AngularJs

$http service can be called to make Ajax calls from Angular 


var app = angular.module('myApp', []).config(/* config stuff */ );
app.PersonFactory = angular.factory('PersonResource', function($http) {
  /* your code here */
  /* when you want to make Ajax calls, use $http */
     .success(function (response) {...})
  /* keep going */

Additionally, if your Persons resource is RESTful, you can just use $resource, ie.

var app = angular.module('myApp', []).... /* setup app */
app.personsFactory = angular.factory('personsFactory', function($resource) {
  var persons = $resource('/api/persons/:id', {id: '@id'});
  return persons;

That way angular will know that on your /api/persons url it can GET persons, it can POST an new person, it can PUT an update for a person and DELETE a person.