AngularJs : Inheritance in Controllers

Here is link of working example : http://jsfiddle.net/premaseem/jwenampL/2/

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});

$scope.name = 'BMW';

}

Link : A nice website to learn AngularJs and Animation : http://www.yearofmoo.com/

http://www.yearofmoo.com/

moo

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: https://egghead.io/lessons/angularjs-isolate-scope-attribute-binding

& 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: https://egghead.io/lessons/angularjs-isolate-scope-expression-binding

= 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: https://egghead.io/lessons/angularjs-isolate-scope-expression-binding

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="http://jenkov.com/theService.json?callback=theServiceResponse&p1=v1&p2=v2"></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 = http://jenkov.com/theService.json?callback=JSON_CALLBACK";
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 http://jenkov.com/theService.json. 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 jenkov.com then that HTML page can only make AJAX calls back to URLs within the jenkov.com domain.

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

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


<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

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

  <script>
    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.