Saturday, 23 May 2015

Sample class paths and terms for java learners

1)All java & oracle related Sample classpaths and compilation, run commonds and java related class paths:

Core java path:
==============

set path=C:\Program Files\Java\jdk1.6.0\bin;

Core java classpath1:
=====================

set classpath=%classpath%;

Core java classpath2:
======================

set classpath=C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0\lib\tools.jar;

Java normal programs compilation & run:
====================================

javac <filename>.java

java <filename>

Java package programs compilation &run:
======================================

javac <filename>.java
          &
javac -d . <filename>.java

java <filename> & java <packagename>/<classname>

Java applet programs compilation &run:
=====================================

javac <filename>.java

appletviewer <filename>.java

For servlet classpath:
======================

set classpath=C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar;%classpath%;

For jsp classpath:
==================

set classpath=C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\jsp-api.jar;%classpath%;

For jstl classpath:
==================

set classpath=E:\JSTL\jakarta-taglibs-standard-1.1.2\lib\jstl.jar;E:\JSTL\jakarta-taglibs-standard-1.1.2\lib\standard.jar;%classpath%;

For struts classpath:
=====================

E:\struts-2.0.11\lib\xwork-2.0.4.jar;E:\struts-2.0.11\lib\struts2-core-2.0.11.jar;
E:\struts-1.3.8\lib\struts-extras-1.3.8.jar;E:\struts-1.3.8\lib\struts-core-1.3.8.jar;

For hibernate classpath:
========================

set classpath=H:\java_work\hibernate-3.2\lib\antlr-2.7.6.jar;H:\java_work\hibernate-3.2\lib\dom4j-1.6.1.jar;
H:\java_work\hibernate-3.2\lib\log4j-1.2.11.jar;H:\java_work\hibernate-3.2\lib\jta.jar;H:\java_work\hibernate-3.2\lib\commons-logging-1.0.4.jar;
H:\java_work\hibernate-3.2\lib\commons-collections-2.1.1.jar;H:\java_work\hibernate-3.2\lib\cglib-2.1.3.jar;H:\java_work\hibernate-3.2\lib\asm.jar;
H:\java_work\hibernate-3.2\lib\ant-antlr-1.6.5.jar;H:\java_work\hibernate-3.2\hibernate3.jar;

For spring classpath:
=====================

set classpath=E:\spring.jar;E:\commons-logging.jar;%classpath%;

For jboss classpath:
==================
set classpath=E:\jboss-5.1.0.GA\client\jbossall-client.jar;.

Glashfish path:
==================

path=C:\Sun\AppServer\bin;%path%;
set classpath=C:\Sun\AppServer\lib\appserv-rt.jar;C:\Sun\AppServer\lib\javaee.jar;%classpath%;

For Weblogic server classpath:
==========================

set classpath=C:\bea\wlserver_10.3\server\lib\weblogic.jar;%classpath%;

For log4j tool classpath:
====================

set classpath=C:\bea\wlserver_10.3\common\lib\log4j.jar;

Oracle ojdbc14 classpath:
=======================

set classpath=C:\oracle\product\10.1.0\db_1\jdbc\lib;C:\oracle\product\10.1.0\db_1\jdbc\lib\ojdbc14.jar;%classpath%;

Oracle path:
============

set path=E:\oracle\product\10.1.0\db_2\bin;E:\oracle\product\10.1.0\db_2\jre\1.4.2\bin\client;
E:\oracle\product\10.1.0\db_2\jre\1.4.2\bin;%SystemRoot%;%SystemRoot%\System32\Wbem;

Mysql path:
============
set path=C:\Program Files\MySQL\MySQL Server 5.0\bin;

2)Create jar,war,rar files by using commond prompt:

jar cf <any name>.jar .

jar cf <any name>.war .

jar cf <any name>.rar .

3)Create Sample.Bat file(Hint:Bat file java file we have to create same directory):

javac swamy.java
java swamy
pause

4)Java JDBC Drivers based on orcle database:

Type 1:
========

sun.jdbc.odbc.JdbcOdbcDriver               [SJOJ]
"jdbc:odbc:oradsn","scott","tiger"         [JOOST]

Type-2:
=======

orcle.jdbc.OracleDriver                    [OJO]
"jdbc:oracle:oci:@<sid>","scott","tiger"   [JOOST]

Type-3:
=======

ids.sql.IDSDriver                                                     [ISI]
jdbc:ids://localhost:12/conn?dsn='oradsn1'&user='scott'&pwd='tiger'   [JILCDUP]

Type 4:
=========

"oracle.jdbc.OracleDriver"                                            [OJO]
"jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"               [JOTL1OST]

5)copy & paste scott user data into Oracle XE(expression edition):
================================================================
step-1:
=======
open oracle(i.e.,where is it instal)--->search for scott.sql & open with notepad--->copy the data

step-2:
=======
      > now, open the SqlCommandPrompt.

      > connected to the database administrator user and password

      > then,connected to the scott user

      > now paste the above scott dataSample class paths and terms for java developers


6) In your Github fork, you need to keep your master branch clean, by clean I mean without any changes, like that you can create at any time a branch from your master. Each time that you want to commit a bug or a feature, you need to create a branch for it, which will be a copy of your master branch.

When you do a pull request on a branch, you can continue to work on another branch and make another pull request on this other branch.

Before creating a new branch, pull the changes from upstream. Your master needs to be up to date.

$ git pull

Create the branch on your local machine and switch in this branch :

$ git checkout -b [name_of_your_new_branch]

Push the branch on github :

$ git push origin [name_of_your_new_branch]

When you want to commit something in your branch, be sure to be in your branch. Add -u parameter to set-upstream.

You can see all the branches created by using :

$ git branch -a

Which will show :

* approval_messages
  master
  master_clean

Add a new remote for your branch :

$ git remote add [name_of_your_remote] [name_of_your_new_branch]

Push changes from your commit into your branch :

$ git push [name_of_your_new_remote] [url]

Update your branch when the original branch from official repository has been updated :

$ git fetch [name_of_your_remote]

Then you need to apply to merge changes if your branch is derivated from develop you need to do :

$ git merge [name_of_your_remote]/develop

Delete a branch on your local filesystem :

$ git branch -d [name_of_your_new_branch]

To force the deletion of local branch on your filesystem :

$ git branch -D [name_of_your_new_branch]

Delete the branch on github :

$ git push origin :[name_of_your_new_branch]

The only difference is the: to say delete, you can do it too by using GitHub interface to remove branch: https://help.github.com/articles/deleting-unused-branches.

If you want to change default branch, it's so easy with GitHub, in your fork go into Admin and in the drop-down list default branch choose what you want.

If you want create a new branch:

$ git branch <name_of_your_new_branch>

Tuesday, 31 March 2015

AngularJS vs Angular

🔹 What is AngularJS?

AngularJS is a JavaScript framework developed by Google for building dynamic, single-page applications (SPAs). It extends HTML with additional attributes and binds data to HTML using expressions.


🔹 1. AngularJS Core Concepts

➤ a. Modules

A module defines the main application container.

js
var app = angular.module('myApp', []);
  • 'myApp' is the application name.

  • [] is where dependencies (like routing) go.


➤ b. Controllers

Controllers are JavaScript functions attached to parts of the HTML to control the data.

js
app.controller('MainController', function($scope) { $scope.message = "Hello from controller!"; });
html
<div ng-controller="MainController"> {{ message }} </div>

➤ c. Directives

Special HTML attributes prefixed with ng-. Examples:

DirectivePurposeExample
ng-appBootstraps Angular<html ng-app="myApp">
ng-modelBinds input to variable<input ng-model="name" />
ng-bindBinds data to element<span ng-bind="name"></span>
ng-controllerDefines controller scope<div ng-controller="MyCtrl">
ng-clickClick event handler<button ng-click="sayHi()">Click</button>
ng-repeatLoops through collections<li ng-repeat="item in list">{{ item }}</li>

➤ d. Two-Way Data Binding

Changes in the view update the model, and vice versa.

html
<input ng-model="name"> <h2>Hello {{ name }}</h2>

➤ e. Expressions

AngularJS expressions are written inside {{ }}.

html
{{ 5 + 5 }} <!-- 10 --> {{ name.toUpperCase() }} <!-- JOHN -->

🔹 2. Example: Hello World AngularJS App

📄 index.html

<!DOCTYPE html> <html ng-app="helloApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <script src="app.js"></script> </head> <body> <div ng-controller="HelloController"> <h1>{{ greeting }}</h1> <input ng-model="greeting"> </div> </body> </html>

📄 app.js

var app = angular.module('helloApp', []); app.controller('HelloController', function($scope) { $scope.greeting = "Hello AngularJS!"; });

🔹 3. Forms and Validation

AngularJS provides built-in form validation.

html
<form name="myForm"> <input type="email" name="userEmail" ng-model="email" required> <span ng-show="myForm.userEmail.$error.required">Required!</span> <span ng-show="myForm.userEmail.$error.email">Invalid email!</span> </form>

🔹 4. Filters

Used to format data in templates.

Filter Usage Example
currency Format as currency `{{ 123
uppercase Upper case `{{ name
date Format dates `{{ today
filter Filter arrays `ng-repeat="x in items

🔹 5. Services

Used to share logic/data across controllers.

Custom Service Example:

js
app.service('MathService', function() {
this.square = function(a) { return a * a; }; });

Inject in Controller:

js
app.controller('CalcController', function($scope, MathService) { $scope.result = MathService.square(4); });

🔹 6. Dependency Injection

AngularJS automatically injects dependencies into functions:

js
app.controller('MyController', function($scope, $http) { // $http is injected });

🔹 7. Routing (SPA)

With ngRoute, you can change views without reloading the page.

Add Script:

html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>

App Configuration:

js

var app = angular.module('myApp', ['ngRoute']); app.config(function($routeProvider) { $routeProvider .when("/", { templateUrl : "main.html" }) .when("/about", { templateUrl : "about.html" }); });

In HTML:

html
<div ng-view></div>

🔹 8. HTTP Requests

Using $http for AJAX calls:

js
app.controller('DataController', function($scope, $http) { $http.get("https://jsonplaceholder.typicode.com/posts") .then(function(response) { $scope.posts = response.data; }); });
html
<div ng-controller="DataController"> <ul> <li ng-repeat="post in posts">{{ post.title }}</li> </ul> </div>

🔹 9. Custom Directives

js
app.directive('myWelcome', function() { return { template: "<h3>Welcome to Custom Directive!</h3>" }; });
html
<my-welcome></my-welcome>

🔹 10. AngularJS vs jQuery

FeatureAngularJSjQuery
TypeFrameworkLibrary
PurposeBuild SPAsDOM Manipulation
Data BindingTwo-wayManual
MVC SupportYesNo

✅ Summary

ConceptDescription
ng-appBootstraps the AngularJS application
ng-modelBinds data between input and model
ng-controllerDefines logic and data for view
ng-repeatLoops through arrays
ng-clickBinds click events
$scopeObject used to share data between view and controller
$httpMakes AJAX requests
$routeProviderConfigures SPA routes
🔹 Basic AngularJS Application Example


angularjs-hello-world/ ├── index.html 👉 View (HTML Template) ├── app/ │ ├── app.module.js 👉 Main App Module (Bootstrap) │ ├── controllers/ │ │ └── hello.controller.js 👉 Controller (Business logic) │ └── models/ │ └── greeting.model.js 👉 Model (Optional - holds static/mock data)

📄 index.html (View)

html

<!DOCTYPE html> <html ng-app="helloApp"> <head> <meta charset="UTF-8"> <title>Hello AngularJS MVC</title> <!-- AngularJS CDN --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script> <!-- App Scripts --> <script src="app/app.module.js"></script> <script src="app/controllers/hello.controller.js"></script> <script src="app/models/greeting.model.js"></script> </head> <body> <div ng-controller="HelloController"> <h1>{{ greeting }}</h1> <input ng-model="greeting" placeholder="Change greeting"> </div> </body> </html>

📄 app/app.module.js (Main App Module)

javascript

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

📄 app/controllers/hello.controller.js (Controller)

javascript

app.controller('HelloController', function($scope, GreetingModel) { // Initialize greeting from model $scope.greeting = GreetingModel.getGreeting(); });

📄 app/models/greeting.model.js (Model)

javascript

app.factory('GreetingModel', function() { var greeting = "Hello AngularJS with MVC!"; return { getGreeting: function() { return greeting; }, setGreeting: function(newGreeting) { greeting = newGreeting; } }; });

💡 Explanation of MVC

ComponentFileRole
Modelgreeting.model.jsHolds and manages greeting data.
Viewindex.htmlHTML that binds to controller data.
Controllerhello.controller.jsConnects model to view via $scope.
Moduleapp.module.jsRegisters and bootstraps app and components.

🔹 Key AngularJS Concepts

ConceptExamplePurpose
ng-model<input ng-model="name">Binds input field to model.
ng-bind<span ng-bind="name"></span>Alternative to {{ name }} interpolation.
ng-repeat<li ng-repeat="item in items">{{ item }}</li>Loop through a list.
ng-click<button ng-click="sayHello()">Click Me</button>Binds a click handler.
ng-show / ng-hide<div ng-show="isVisible">Conditionally show/hide elements.


🔹 AngularJS vs Angular (2+)

FeatureAngularJS (1.x)Angular (2+)
LanguageJavaScriptTypeScript
ArchitectureMVCComponent-based
PerformanceSlowerFaster
Mobile SupportNoYes
SupportDeprecatedActively maintained

🔹 When to Use AngularJS Today

Good for:

  • Maintaining existing projects

  • Legacy applications in enterprises

  • Quick internal tools/prototypes

Not recommended for:

  • New production apps (use Angular 15+, React, or Vue.js)


Modern Angular (TypeScript-based) with a proper Angular project structure.

angular-hello-world/
├── src/
│   ├── app/
│   │   ├── greeting/
│   │   │   ├── greeting.component.ts       👉 Component (View + Controller)
│   │   │   ├── greeting.component.html     👉 View Template
│   │   │   ├── greeting.component.css      👉 Component-specific styles
│   │   │   └── greeting.service.ts         👉 Service (Model/logic)
│   │   └── app.module.ts                   👉 Root Module (Bootstrap)
│   └── main.ts                             👉 Entry Point
├── angular.json                            👉 Angular CLI config
├── package.json                            👉 Project dependencies

📦 Step-by-Step with Code

1️⃣ Create Project using Angular CLI

npm install -g @angular/cli
ng new angular-hello-world --routing=false --style=css
cd angular-hello-world

2️⃣ Generate Component and Service

ng generate component greeting
ng generate service greeting/greeting

3️⃣ app.module.ts – Root Module

// src/app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { GreetingComponent } from './greeting/greeting.component';

@NgModule({
  declarations: [AppComponent, GreetingComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

4️⃣ greeting.service.ts – Service (Model Equivalent)

// src/app/greeting/greeting.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class GreetingService {
  private greeting = "Hello Angular (v17) with MVC structure!";

  getGreeting(): string {
    return this.greeting;
  }

  setGreeting(newGreeting: string) {
    this.greeting = newGreeting;
  }
}

5️⃣ greeting.component.ts – Component (Controller + View Logic)

// src/app/greeting/greeting.component.ts

import { Component, OnInit } from '@angular/core';
import { GreetingService } from './greeting.service';

@Component({
  selector: 'app-greeting',
  templateUrl: './greeting.component.html',
  styleUrls: ['./greeting.component.css']
})
export class GreetingComponent implements OnInit {
  greeting: string = '';

  constructor(private greetingService: GreetingService) {}

  ngOnInit() {
    this.greeting = this.greetingService.getGreeting();
  }
}

6️⃣ greeting.component.html – View Template

<!-- src/app/greeting/greeting.component.html -->
<h1>{{ greeting }}</h1>
<input [(ngModel)]="greeting" placeholder="Change greeting">

7️⃣ app.component.html – App Root Template

<!-- src/app/app.component.html -->
<app-greeting></app-greeting>

✅ Result
When you run:

ng serve

You’ll see the below output:

Hello Angular (v17) with MVC structure!


🔁 Comparison: AngularJS vs Angular (Modern)

Feature AngularJS Angular (2+ / latest)
Language JavaScript TypeScript
Component Model Controller + Template Component (Class + Template + Metadata)
Module System Manual via script tags NgModules with @NgModule decorator
Dependency Injection Basic Hierarchical, powerful DI
Forms ng-model Template-driven or Reactive Forms
Routing ngRoute @angular/router
Build Tooling Manual or Grunt/Gulp Angular CLI + Webpack

✅ Summary of Modern Angular MVC Analogy

MVC Concept Angular
Model Service (e.g., GreetingService)
View HTML template (e.g., greeting.component.html)
Controller Component class (e.g., GreetingComponent)
Bootstrap Module (AppModule)


Thursday, 19 March 2015

CSS


All CSS Border Properties

border Sets all the border properties in one declaration
border-bottom Sets all the bottom border properties in one declaration
border-bottom-color Sets the color of the bottom border
border-bottom-style Sets the style of the bottom border
border-bottom-width Sets the width of the bottom border
border-color Sets the color of the four borders
border-left Sets all the left border properties in one declaration
border-left-color Sets the color of the left border
border-left-style Sets the style of the left border
border-left-width Sets the width of the left border
border-right Sets all the right border properties in one declaration
border-right-color Sets the color of the right border
border-right-style Sets the style of the right border
border-right-width Sets the width of the right border
border-style Sets the style of the four borders
border-top Sets all the top border properties in one declaration
border-top-color Sets the color of the top border
border-top-style Sets the style of the top border
border-top-width Sets the width of the top border
border-width Sets the width of the four borders

All CSS Dimension Properties

height Sets the height of an element auto
length
%
inherit
max-height Sets the maximum height of an element none
length
%
inherit
max-width Sets the maximum width of an element none
length
%
inherit
min-height Sets the minimum height of an element length
%
inherit
min-width Sets the minimum width of an element length
%
inherit
width Sets the width of an element auto
length
%
inherit

Monday, 16 March 2015

CSS Font Properties


All CSS Font Properties

font
Sets all the font properties in one declaration
font-family 
Specifies the font family for text
font-size
Specifies the font size of text
font-style 
Specifies the font style for text
font-variant
Specifies whether or not a text should be displayed in a small-caps font
font-weight 
Specifies the weight of a font

CSS Text Properties


All CSS Text Properties

color
Sets the color of text

direction
Specifies the text direction/writing direction

letter-spacing
Increases or decreases the space between characters in a text

line-height
Sets the line height

text-align
Specifies the horizontal alignment of text

text-decoration
Specifies the decoration added to text

text-indent
Specifies the indentation of the first line in a text-block

text-shadow
Specifies the shadow effect added to text

text-transform
Controls the capitalization of text

unicode-bidi
Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document

vertical-align
Sets the vertical alignment of an element

white-space
Specifies how white-space inside an element is handled

word-spacing
Increases or decreases the space between words in a text

Tuesday, 10 March 2015

AngularJs Scopes & UI Router & Share data between controllers

There are four types of scopes:
1.  normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with scope: true
2.  normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
3.  isolate scope -- directive with scope: {...}. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
4.  transcluded scope -- directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.
For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.

---------------------------------------------------------------------------------------------------------

   There are two ways to  share data between controllers.
1) Using a service or exploiting depending parent/child relation between controller scopes.
In this post, we’ll analyze the last one method.

   It is possible to send data from parent controller to a child controller and viceversa.
To transmit data from the FirstController to SecondController, which the scope of the first one is parent to the scope of the second one, it should use $broadcast method in the FirstController.

angular.module('myApp', [])
.controller('ParentCtrl', ['$scope', function($scope) {
$scope.message = "Child updated from parent controller";

$scope.clickFunction = function() {
$scope.$broadcast('update_parent_controller', $scope.message);
};
}
])
.controller('ChildCtrl', ['$scope', function($scope) {
$scope.message = "Some text in child controller";

$scope.$on("update_parent_controller", function(event, message) {
$scope.message = message;
});
}
]);

Here a plunker for a live demo.

2)  Instead, if it need to send data from the SecondController (child) to the FirstController (parent), it should use the $emit method.

angular.module('myApp', [])
.controller('ParentCtrl', ['$scope', function ($scope) {
$scope.message = "Some text in parent";
$scope.$on("update_parent_controller", function(event, message){
$scope.message = message;
});

}])
.controller('ChildCtrl', ['$scope', function ($scope) {
$scope.clickFunction = function() {
$scope.message = "Parent updated";

$scope.$emit('update_parent_controller', $scope.message);
}

}]);

Here a plunker for a live demo.

   Finally, here a little trick where two controller have no parent/child relationship.
It should pass data from one controller through $rootScope and the $broadcast method.

angular.module('myApp', [])
.controller('FirstCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.message = "Clicked!";
$rootScope.clickFunction = function() {
$rootScope.$broadcast("Update", $scope.message);
};
}])
.controller('SecondCtrl', ['$scope','$rootScope', function($scope,$rootScope) {
$scope.message = "Waiting for a click...";

$rootScope.$on("Update", function(event, message) {
$scope.message = message;
});
}]);

Here a plunker for a live demo.

   In many scenarios, the data needs to be shared between different scopes. There are different ways to share the data among the scopes. The proper one can be chosen based on the need.

1. Sharing data between Parent scope and Child scope

If Parent-Child relationship can be established, then the data sharing can be implemented as follows.

In AngularJS, Scopes inherits prototypically. ie. In simple terms, if the property is not defined in the child scope, it will be accessed from the parent’s scope. The parent scope’s member variable can be accessed by “$scope.$parent” property from child’s scope.

Javascriptfunction Parent($scope) { $scope.x= 5; $scope.y= 5; } function Child($scope) { $scope.modifyBothScopes= function() { $scope.$parent.x++; }; $scope.modifyonlyChildscope= function() { // member "y" will be created in the child scope // So, after the following statment, $scope.$parent.y++ will only increment the parent scope. // It would not affect the child scope. $scope.y++; }; }

Html<div ng-controller="Parent"> parentX = {{x}} <br/> parentY = {{y}}<br/> <div ng-controller="Child"> childX = {{x}}<br/> childY = {{y}}<br/> <a ng-click="modifyBothScopes()">modifyBothScopes</a><br> <a ng-click="modifyonlyChildscope()">modifyonlyChildscope</a> </div> </div>​

JS Fiddle

http://jsfiddle.net/ramandv/JHwxP/

2. Sharing data using Service [like a global variable]

To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

In the following example, Service is used to store the variable x. The independent controllers will check the value of X whenever needed.

Javascriptangular.module('myApp', []) .service('myService', function () { var x=5 ; return { increase : function() { x++; }, getX : function() { return x; } }; }) function ControllerA($scope, myService) { $scope.x = 1; $scope.incrementDataInService= function() { myService.increase(); } $scope.syncDataWithService= function() { $scope.x = myService.getX(); } } function ControllerB($scope, myService) { $scope.x = 1; $scope.incrementDataInService= function() { myService.increase(); } $scope.syncDataWithService= function() { $scope.x = myService.getX(); } }​​
HTML<div ng-app="myApp"> <div ng-controller="ControllerA"> ControllerA.X = {{x}}<br/> <a ng-click="incrementDataInService()">incrementDataInService</a><br> <a ng-click="syncDataWithService()">syncDataWithService</a><br> </div> <hr/> <div ng-controller="ControllerB"> ControllerB.X = {{x}}<br/> <a ng-click="incrementDataInService()">incrementDataInService</a><br> <a ng-click="syncDataWithService()">syncDataWithService</a><br> </div> </div>​​

JS Fiddle

http://jsfiddle.net/ramandv/kR859/

3. Sharing data using Service – monitor the changes

In some times, it is important to monitor the changes in the service. AngularJS provides “$broadcast” to broadcast the data to the listening subscribers.

The following contrived example shows the usage of $broadcast. The ControllerA and ControllerB subscribed to the event “XChanged”. The service “myService” will broadcast the event “XChanged” when the value of “x” changes.

Javascriptangular.module('myApp', []) .service('myService', function ($rootScope) { var x=5 ; return { increase : function() { x++; $rootScope.$broadcast('XChanged', x); } }; }) function ControllerA($scope, myService) { $scope.x = 1; $scope.incrementDataInService= function() { myService.increase(); } $scope.$on('XChanged', function(event, x) { $scope.x = x; }); } function ControllerB($scope, myService) { $scope.x = 1; $scope.incrementDataInService= function() { myService.increase(); } $scope.$on('XChanged', function(event, x) { $scope.x = x; }); }​​

HTML<div ng-app="myApp"> <div ng-controller="ControllerA"> ControllerA.X = {{x}}<br/> <a ng-click="incrementDataInService()">incrementDataInService</a><br> </div> <hr/> <div ng-controller="ControllerB"> ControllerB.X = {{x}}<br/> <a ng-click="incrementDataInService()">incrementDataInService</a><br> </div> </div>

JS Fiddle

http://jsfiddle.net/ramandv/25CVc/
---------------------------------------------------------------------------------------
AngularUI Router
   AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.
   Check out the sample app: http://angular-ui.github.io/ui-router/sample/
Note: UI-Router is under active development. As such, while this library is well-tested, the API may change. Consider using it in production applications only if you're comfortable following a changelog and updating your usage accordingly.
Get Started
(1) Get UI-Router in one of the following ways:
•   clone & build this repository
•   download the release (or minified)
•   via Bower: by running $ bower install angular-ui-router from your console
•   or via npm: by running $ npm install angular-ui-router from your console
•   or via Component: by running $ component install angular-ui/ui-router from your console
(2) Include angular-ui-router.js (or angular-ui-router.min.js) in your index.html, after including Angular itself (For Component users: ignore this step)
(3) Add 'ui.router' to your main module's list of dependencies (For Component users: replace'ui.router' with require('angular-ui-router'))
When you're done, your setup should look similar to the following:
<!doctype html>
<html ng-app="myApp">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script src="js/angular-ui-router.min.js"></script>
    <script>
        var myApp = angular.module('myApp', ['ui.router']);
        // For Component users, it should look like this:
        // var myApp = angular.module('myApp', [require('angular-ui-router')]);
    </script>
    ...
</head>
<body>
    ...
</body>
</html>
Nested States & Views
The majority of UI-Router's power is in its ability to nest states & views.
(1) First, follow the setup instructions detailed above.
(2) Then, add a ui-view directive to the <body /> of your app.
<!-- index.html -->
<body>
    <div ui-view></div>
    <!-- We'll also add some navigation: -->
    <a ui-sref="state1">State 1</a>
    <a ui-sref="state2">State 2</a>
</body>
(3) You'll notice we also added some links with ui-sref directives. In addition to managing state transitions, this directive auto-generates the href attribute of the <a /> element it's attached to, if the corresponding state has a URL. Next we'll add some templates. These will plug into the ui-viewwithin index.html. Notice that they have their own ui-view as well! That is the key to nesting states and views.
<!-- partials/state1.html -->
<h1>State 1</h1>
<hr/>
<a ui-sref="state1.list">Show List</a>
<div ui-view></div>
<!-- partials/state2.html -->
<h1>State 2</h1>
<hr/>
<a ui-sref="state2.list">Show List</a>
<div ui-view></div>
(4) Next, we'll add some child templates. These will get plugged into the ui-view of their parent state templates.
<!-- partials/state1.list.html -->
<h3>List of State 1 Items</h3>
<ul>
  <li ng-repeat="item in items">{{ item }}</li>
</ul>
<!-- partials/state2.list.html -->
<h3>List of State 2 Things</h3>
<ul>
  <li ng-repeat="thing in things">{{ thing }}</li>
</ul>
(5) Finally, we'll wire it all up with $stateProvider. Set up your states in the module config, as in the following:
myApp.config(function($stateProvider, $urlRouterProvider) {
  //
  // For any unmatched url, redirect to /state1
  $urlRouterProvider.otherwise("/state1");
  //
  // Now set up the states
  $stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: "partials/state1.html"
    })
    .state('state1.list', {
      url: "/list",
      templateUrl: "partials/state1.list.html",
      controller: function($scope) {
        $scope.items = ["A", "List", "Of", "Items"];
      }
    })
    .state('state2', {
      url: "/state2",
      templateUrl: "partials/state2.html"
    })
    .state('state2.list', {
      url: "/list",
      templateUrl: "partials/state2.list.html",
      controller: function($scope) {
        $scope.things = ["A", "Set", "Of", "Things"];
      }
    });
});
(6) See this quick start example in action.
Go to Quick Start Plunker for Nested States & Views
(7) This only scratches the surface
Dive Deeper!
Multiple & Named Views
Another great feature is the ability to have multiple ui-views view per template.
Pro Tip: While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.
(1) Follow the setup instructions detailed above.
(2) Add one or more ui-view to your app, give them names.
<!-- index.html -->
<body>
    <div ui-view="viewA"></div>
    <div ui-view="viewB"></div>
    <!-- Also a way to navigate -->
    <a ui-sref="route1">Route 1</a>
    <a ui-sref="route2">Route 2</a>
</body>
(3) Set up your states in the module config:
myApp.config(function($stateProvider) {
  $stateProvider
    .state('index', {
      url: "",
      views: {
        "viewA": { template: "index.viewA" },
        "viewB": { template: "index.viewB" }
      }
    })
    .state('route1', {
      url: "/route1",
      views: {
        "viewA": { template: "route1.viewA" },
        "viewB": { template: "route1.viewB" }
      }
    })
    .state('route2', {
      url: "/route2",
      views: {
        "viewA": { template: "route2.viewA" },
        "viewB": { template: "route2.viewB" }
      }
    })
});