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.

What are AngularJs services

Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

Angular services are:

  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

Angular offers several useful services (like $http), but for most applications you’ll also want to create your own.

The services are singleton objects or functions that carry out specific tasks. It holds some business logic. Separation of concern is at the heart while designing an AngularJS application. Your controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.

For that we must create singleton objects called services. AngularJS can manage these service objects. Wherever we want to use the service, we just have to specify its name and AngularJS auto-magically inject these objects (more on this later).

Thus service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters etc. Thus we can divide our application in logical units. The business logic or logic to call HTTP url to fetch data from server can be put within a service object.

Putting business and other logic within services has many advantages. First it fulfills the principle of separation of concern or segregation of duties. Each component is responsible for its own work making application more manageable. Second this way each component can be more testable. AngularJS provides first class support for unit testing. Thus we can quickly write tests for our services making them robust and less error prone.

angularjs service diagram

Consider above diagram. Here we divide our application in two controllers: 1. Profile and 2. Dashboard. Each of these controllers require certain user data from server. Thus instead of repeating the logic to fetch data from server in each controller, we create a User service which hides the complexity. AngularJS automatically inject User service in both Profile and Dashboard controller. Thus our application becomes for modular and testable.


AngularJS internal services

AngularJS internally provides many services that we can use in our application. $http is one example (Note: All angularjs internal services starts with $ sign). There are other useful services such as $route,$window, $location etc.

These services can be used within any Controller by just declaring them as dependencies. For example:

module.controller('FooController', function($http){



module.controller('BarController', function($window){




AngularJS custom services

We can define our own custom services in angular js app and use them wherever required.

There are several ways to declare angularjs service within application. Following are two simple ways:

var module = angular.module('myapp', []);

module.service('userService', function(){

this.users = ['John', 'James', 'Jake'];


or we can use factory method

module.factory('userService', function(){

var fac = {};

fac.users = ['John', 'James', 'Jake'];

return fac;


Both of the ways of defining a service function/object are valid. We will shortly see the difference between factory() and service() method. For now just keep in mind that both these apis defines a singleton service object that can be used within any controller, filter, directive etc.