Wednesday, 24 February 2016

SQL Server Query for Enabling Change Data Capture On All Tables

  1. create procedure sp_enable_disable_cdc_all_tables(@dbname varchar(100), @enable bit)  
  2. as  
  3.   
  4. BEGIN TRY  
  5. DECLARE @source_name varchar(400);  
  6. declare @sql varchar(1000)  
  7. DECLARE the_cursor CURSOR FAST_FORWARD FOR  
  8. SELECT table_name  
  9. FROM INFORMATION_SCHEMA.TABLES where TABLE_CATALOG=@dbname and table_schema='dbo' and table_name != 'systranschemas'  
  10. OPEN the_cursor  
  11. FETCH NEXT FROM the_cursor INTO @source_name  
  12.   
  13. WHILE @@FETCH_STATUS = 0  
  14. BEGIN  
  15. if @enable = 1  
  16.   
  17. set @sql =' Use '+ @dbname+ ';EXEC sys.sp_cdc_enable_table  
  18.             @source_schema = N''dbo'',@source_name = '+@source_name+'  
  19.           , @role_name = N'''+'dbo'+''''  
  20.             
  21. else  
  22. set @sql =' Use '+ @dbname+ ';EXEC sys.sp_cdc_disable_table  
  23.             @source_schema = N''dbo'',@source_name = '+@source_name+',  @capture_instance =''all'''  
  24. exec(@sql)  
  25.   
  26.   
  27.   FETCH NEXT FROM the_cursor INTO @source_name  
  28.   
  29. END  
  30.   
  31. CLOSE the_cursor  
  32. DEALLOCATE the_cursor  
  33.   
  34.       
  35. SELECT 'Successful'  
  36. END TRY  
  37. BEGIN CATCH  
  38. CLOSE the_cursor  
  39. DEALLOCATE the_cursor  
  40.   
  41.     SELECT   
  42.         ERROR_NUMBER() AS ErrorNumber  
  43.         ,ERROR_MESSAGE() AS ErrorMessage;  
  44. END CATCH  

Introduction To CDC (Change Data Capture) Of SQL Server - Part One

In this article, we will look intoa  SQL Server feature, called CDC, used for tracking/auditing database changes at table level. This feature will help us to track database changes like INSERT, UPDATE and DELETE on tables. 

It even tracks old and new values for an update operation. CDC uses SQL Server transaction logs for capturing all inserts, updates, and deletes on a table. This feature is available on 2008 or higher versions and part of enterprise editions. Let’s open management studio and enable CDC on EmployeeDB to track the changes by following the below steps:

Enable CDC on a database by running the following command, it needs sysadmin privileges.

Enable CDC
Create a role to which we will give access to CDC tables (which will hold all data changes) using the following command:
  1. CREATEROLEcdc_role  
We need to select tables on which tracking should be enabled by running the following command:
  1. EXECsys.sp_cdc_enable_table  
  2. @source_schema='dbo',-- Schema name  
  3. @source_name='employees',-- Table Name  
  4. @role_name=N'cdc_role'-- Role having access on CDC tables [having data audit details]  
This will start SQL jobs to track changes done to employees table. If you expand Tables node and go toSystem Tables in Object Explorer, there will be a table employees_CT with exact schema of employees to hold data changes:

CDC  

Select query

Let’s test CDC by doing some changes to employees table:

employees table

Let’s query our tracking table [dbo_employees_CT]:

result

If column _$operation is 1 it means it’s a DELETE operation; 2 means INSERT; 3 means Value before UPDATE; and 4 means Values after UPDATE. We will write the following query to get results more meaningfully:

DELETE operation

Apart from dbo_employees_CT table, we have other tables created by CDC under System Tables to store metadata for its tracking purpose. Let’s understand purpose of each:

Captured_columns: It has all column’s details on which CDC is enabled:

details

Change_tables: It contains capture details like table name, role name etc along start and end lsn. Any change on a table is uniquely identified by LSN (log sequence number).

contains capture details

ddl_history: It contains information on any schema changes on the tracking table [employees] like adding\removing a column. Here, I added a new column location.

contains information

index_columns: It contains index details of tables on which tracking is enabled. 

contains index details

lsn_time_mapping: It contains mapping details of table change’s LSN and its time of occurrence:

contains mapping details

I am ending things here. In next article, we will drill down more on CDC. I hope this article will be helpful for all.
 

Two options to store user friendly column names in SQL Server

Problem
Report-writing often involves putting labels on columns for easy recognition by the end users. Sometimes these labels change as the business changes and different users adopt the system. Are there any easy ways to automate displaying user-friendly column names with a minimum amount of rework in reports? Check out this tip to learn more.
Solution
This article will review two approaches to storing user-friendly output in SQL Server itself. The first option that will be outlined is using SQL Server Extended Properties. The second option is using SQL Server Views.

SQL Server Extended Properties

SQL Server allows classes of documentation to be written into the database. See Using Extended Properties on Database Objects for the complete list. This tip will focus on columns and tables for use with user-readable output.
Starting with the basics, below is a script that creates a database, table and adds two column captions.
Extended Property creation code
use master
go
if db_id('SQLTips_UFOutput') > 0
 drop database SQLTips_UFOutput
go
create database SQLTips_UFOutput
go
use SQLTips_UFOutput
go
create table person (
 pers_id int identity(1,10) not null,
 pers_fname varchar(50) not null,
 pers_ssn varchar(12) not null,
 constraint PK_pers primary key (pers_id)
)
insert into person values 
 ('John', '123-45-6789'),
 ('Luke', '987-00-1249'),
 ('Janet', '232-34-3208')
EXEC sp_addextendedproperty 
@name = N'Caption', @value = 'First name',
@level0type = N'Schema', @level0name = dbo,
@level1type = N'Table',  @level1name = person,
@level2type = N'Column', @level2name = pers_fname;
GO
EXEC sp_addextendedproperty 
@name = N'Caption', @value = 'Social Security number',
@level0type = N'Schema', @level0name = dbo,
@level1type = N'Table',  @level1name = person,
@level2type = N'Column', @level2name = pers_ssn;
GO


Confirm the text is saved by calling a function with parameter values that drill down to the table.
Extended Property retrieval code
select * from fn_listextendedproperty(
 'caption', 
 N'schema', 'dbo', 
 N'table', 'person', 
 N'column', default
)


sql server extened properties
Alright, so that gets the values into the database. How do we display them? Check out the code below.
Extended Property integration into result set
declare @dynSQL nvarchar(4000), -- SQL command the run built using the captions
 @colName varchar(50), -- SQL column name
 @colAlias varchar(50), -- Caption defined as an extendedproperty
 @comma bit -- flag used for proper SQL string-building
declare colAlias cursor for
select cast(exprop.objname as varchar), cast(exprop.value as varchar)
from fn_listextendedproperty(
  'caption', 
  N'schema', 'dbo', 
  N'table', 'person', 
  'column', default
 ) exprop
 -- if every column has an extended property; scroll down for a left join example
 inner join sys.columns syscol on 
  cast(exprop.objname as varchar) collate SQL_Latin1_General_CP1_CI_AS = 
  cast(syscol.name as varchar) collate SQL_Latin1_General_CP1_CI_AS 
  -- these casts are explained below
-- initialize output string
set @dynSQL = 'select '
set @comma = 0
-- output each column name and alias
open colAlias
fetch from colAlias into @colName, @colAlias
while @@fetch_status = 0 begin
 if @comma = 1 set @dynSQL = @dynSQL + ', '
 set @dynSQL = @dynSQL + quotename(@colName) + ' as ' + quotename(@colAlias)
 set @comma = 1
 fetch next from colAlias into @colName, @colAlias
end
close colAlias
deallocate colAlias
set @dynSQL = @dynSQL + ' from person'
exec sp_executeSQL @dynSQL
The dynamic SQL above writes this statement that gets executed:
Results of dynamic SQL above
select [pers_fname] as [First name], [pers_ssn] as [Social Security number] from person

results of dynamic sql
So why are there so many casts in the code above? They are used in response to this error message: Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AI" in the equal to operation. Good thing we're skilled mediators.
The above could be taken one step further to have the statement which writes the text "person" as a parameter and table name dynamic-generated as well. That would be all that's needed for user-friendly output once the captions have been added to tables.

Adding captions to every table seems redundant in cases where columns are fine as they are. This query uses a caption if there is one, otherwise the column name:
Retrieving Extended Properties or their column names when no captions exist
select 
 coalesce(cast(exprop.objname as varchar) collate SQL_Latin1_General_CP1_CI_AS,
  syscol.name) as colname, 
 coalesce(cast(exprop.value as varchar) collate SQL_Latin1_General_CP1_CI_AS,
  syscol.name) as colalias
from sys.columns syscol 
 left outer join fn_listextendedproperty(
   'caption', 
   N'schema', 'dbo', 
   N'table', 'person', 
   'column', default
  ) exprop on
  cast(exprop.objname as varchar) collate SQL_Latin1_General_CP1_CI_AS = 
  cast(syscol.name as varchar) collate SQL_Latin1_General_CP1_CI_AS 
where syscol.object_id = object_id('person')


retrieving extended properties


Here are a few notes on this code:
  • The source table is sys.columns which may include unneeded columns in the report.
  • The coalesces simply pick the first non-null value, and because all data types in its invocation need to be the same, that 43-character cast in needed.
  • To use this query, simply replace the above cursor query with it.
Suppose in looking at the output, the word "number" is too wide in "Social Security Number". Here's how to shorten the column name:
Extended Properties updating
exec sp_updateextendedproperty 
@name = N'Caption', @value = 'Social Security #',
@level0type = N'Schema', @level0name = dbo,
@level1type = N'Table', @level1name = person, 
@level2type = N'Column',@level2name = pers_ssn;
GO
For completeness, here's how to remove an extended property:
Extended Properties deleting
exec sp_dropextendedproperty 
@name = N'Caption',
@level0type = N'Schema', @level0name = dbo,
@level1type = N'Table', @level1name = person, 
@level2type = N'Column',@level2name = pers_ssn;
GO
One extra benefit of extended property method is their applicability to all SQL objects. For a complete list of objects, see Next Steps.
Extended Properties creation for a table
EXEC sp_addextendedproperty 
@name = N'Caption', @value = 'Company Personnel',
@level0type = N'Schema', @level0name = dbo,
@level1type = N'Table',  @level1name = person;
GO
select * from fn_listextendedproperty(null, N'schema', 'dbo', N'table', 'person', default, default)
One unfortunate drawback of fn_listextendedproperty() is that for columns, it has to pick a specific table. For instance, the "N'table', default, default, default" parameters return all table properties. While the "N'table', default, N'column', default" parameters returns a NULL record set. This would have been ideal because creating a view with only the desired columns serves as a workaround since only relevant columns would exist.
I applaud anyone that has read this far as that is an amount of code that may need cut down to reach production given the pace of organization and level of commitment to documentation. This next method recreates the ability to have user-friendly column names with far less typing.

Views

If there's only an interest in column or table aliasing, it's also possible to use views as opposed to the extended properties, without as much overhead. Here is an example:
View creation for user-friendly columns
create view vuf_person as -- vuf = view user-friendly
select pers_fname as [First name],
 pers_ssn as [Social Security number]
from person
go
select * from vuf_person


view creation for user friendly columns
To update the column name, simply ALTER the VIEW. Note: if a view is dropped and/or re-created, any previously issued security statements must be reassigned.
View updating for user-friendly columns
alter view vuf_person as
select pers_fname as [First name],
 pers_ssn as [Social Security #]
from person
go
select * from vuf_person


updating for user friendly columns
To emulate the object-level captioning of extended properties, name the view what's desired in the output:
View creation for user-friendly table names
create view [Personnel Report] as
select pers_fname as [First name],
 pers_ssn as [Social Security #]
from person
go
select * from [Personnel Report]
With this approach, user-friendly views could start with similar names, such "vuf_Personnel Report", and the reporting tools that lists available views could remove the first four characters.
Next Steps

  • Decide what level of documentation to store in the database
  • If only column- and table-level captions are needed, the view option is possible and requires less code
  • Consider isolating new tables with user-friendly views that use human-readable aliases
  • Use those views in SSRS and enjoy how the column names are user-friendly without any work
  • Create an interface for users to allow updating the view column aliases that uses a dynamically-generated ALTER VIEW statement
  • Read more about sp_addextendedproperty, sp_updateextendedproperty, sp_deleteextendedproperty and the complete list of extended properties
  • Be creative. What else could these captions be used for? How else could they be organized? Are there any other extended properties that seem useful in your environment?

Tuesday, 2 February 2016

Start With AngularJS: Part 7

Thank you for reading my previous articles. If you have not read them, then study from the following links. After reading them it will be easier to understand today’s topics.
Routing in AngularJS

It helps us to divide your app into multiple view and bind it different views to Controllers. A route is specified in the URL after the # sign.

Like:
$ rout Provider taken care by AngularJS. To define the routes for your app$route Provider service provides method when () and otherwise ().

Example:

  1. var sampleApp = angular.module('sampleApp', []);  
  2.   
  3. sampleApp.config(['$routeProvider',  
  4.     function($routeProvider)  
  5.     {  
  6.         $routeProvider.  
  7.         when('/ShowOrder/:orderId',  
  8.         {  
  9.             templateUrl: 'templates/show_order.html',  
  10.             controller: 'ShowOrderController'  
  11.         });  
  12.     }  
  13. ]);  
  14. sampleApp.controller('ShowOrderController', function($scope, $routeParams)  
  15.  {  
  16.   
  17.     $scope.order_id = $routeParams.orderId;  
  18.   
  19. });  
AngularJS Events

That directive allows you to run its functions at user event. It is not overwriting with HTML5 event. In page both events can be executed at a time.

It has several types:
  • Ng-Mouse enters: it execute of mouse when itenter on element area.
  • Ng-mouse over: it execute of mouse when it over on element area.
  • Ng-mouse move: it execute of mouse when it move on element area.
  • Ng-mouse leave: it execute of mouse when it leave on element area.
  • Ng-mouse down: it execute of mouse when it down on element area.
  • Ng-mouse up: it execute of mouse when it up on element area.
  • Ng-click: it execute when click on element area.
  • Ng-change: it execute when changed on element area.
  • Ng-key press: After key press that event execute.
  • Ng-Submit: it execute of mouse click on element area.
  • Ng-blur: it execute after blur on element area.
  • Ng-copy: it execute after copy text on element area.
  • Ng-cut: it execute after cut text on element area.
  • Ng-dblclick: it execute after dbl click on element area.
  • Ng-focus: it execute after focusing on element area.
  • Ng-paste: it execute after paste on element area.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Event Demo</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  7.         </script>  
  8.   
  9. </head>  
  10.   
  11. <body>  
  12.     <h3> Angular JS change Events</h3>  
  13.     <br/>  
  14.   
  15.     <script>  
  16.         var app = angular.module("app", []);  
  17.         app.controller("ChangeController", function($scope)  
  18.         {  
  19.   
  20.             $scope.CheckBoxChanged = function()   
  21.             {  
  22.                 $scope.CheckBoxStatus = $scope.chkValue;  
  23.             };  
  24.             $scope.KeyDown = function()   
  25.             {  
  26.                 $scope.keydown = " Key down executes " + new Date().getTime();  
  27.             }  
  28.             $scope.TextBoxChanged = function()  
  29.             {  
  30.                 $scope.TextBoxStatus = $scope.txtValue;  
  31.             };  
  32.             $scope.KeyPress = function()   
  33.             {  
  34.                 $scope.keypress = " Key press executes " + new Date().getTime();  
  35.             }  
  36.             $scope.DropDownChnaged = function()  
  37.             {  
  38.                 $scope.DropDownStatus = $scope.dropValue;  
  39.             };  
  40.   
  41.         });  
  42.     </script>  
  43.     <div ng-app="app" ng-controller="ChangeController">  
  44.         <input type="checkbox" name="chk1" ng-model="chkValue" ng-change="CheckBoxChanged()" />  
  45.         <p>Check box status: {{ CheckBoxStatus }}</p>  
  46.         <br/>  
  47.         <inputtype="text" name="txt1" ng-model="txtValue" ng-change="TextBoxChanged()" />  
  48.         <p>Text box status: {{ TextBoxStatus }}</p>  
  49.         <input type="text" ng-keydown="KeyDown()" ng-keypress="KeyPress()" ng-keyup="KeyUp()" />  
  50.         <br/>  
  51.         <p>Key down - {{ keydown }}</p>  
  52.         <p>Key press - {{ keypress }}</p>  
  53.   
  54.         <br/>  
  55.         <select name="dropChange" ng-model="dropValue" ng-change="DropDownChnaged()">  
  56.             <option value="Male">Male</option>  
  57.                 <option value="Female">Female</option>  
  58.                     </select>  
  59.                     <p>Dropdown box status: {{ DropDownStatus }}</p>  
  60.                     </div>  
  61. </body>  
  62.   
  63. </html>  
  64. <!DOCTYPE html>  
  65. <html>  
Output

output

I hope you will understand and will practice with my demo. 

Monday, 1 February 2016

Start With AngularJS: Part 6

Thank you for reading my previous article. If you have not read that, then study from the following links. After reading them it would be easier to understand today’s topics.
Today you will study about AngularJS services.

What is a Service

Services are JavaScript functions and are responsible to do specific tasks only. AngularJS has about 30 built-in services. One of them is the $location, $http, $provide, $resource, $window, $parse service.

Different ways to create service in AngularJS: Factory

Factory is a simple function which allows you to add some logic before creating the object. It returns the created object.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Factory Demo</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  7.         </script>  
  8.         <script>  
  9.             var app = angular.module('app', []);  
  10.             app.controller("MemberController", function($scope, myFactory)  
  11.             {  
  12.                 $scope.FirstName = myFactory.FirstName;  
  13.                 $scope.FullName = myFactory.FullName;  
  14.             });  
  15.             app.factory('myFactory', function()  
  16.                {  
  17.                 varmyName = "Shiva";  
  18.                 function getName()   
  19.                 {  
  20.                     return myName;  
  21.                 }  
  22.                 return   
  23.                 {  
  24.                     FullName: getName() + " " + "shukla",  
  25.                     FirstName: getName()  
  26.                 };  
  27.             });  
  28.         </script>  
  29. </head>  
  30. <body ng-app="app">  
  31.     <p>AngularJS Factory</p>  
  32.   
  33.   
  34.     <div ng-controller="MemberController">  
  35.         <p>  
  36.             FirstName: {{FirstName}}  
  37.         </p>  
  38.         <p>  
  39.             FullName: {{FullName}}  
  40.         </p>  
  41.         </div>  
  42.         </body>  
  43.   
  44. </html>  
Output

output

When to use: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with constructor function.

Service:

Service is a constructor function which creates the object using new keyword. You can add properties and functions to a service object by using this keyword. Unlike factory, it doesn’t return anything.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Service Demo</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  7.         </script>  
  8.         <script>  
  9.             var app = angular.module('app', []);  
  10.             app.controller('MemberController', function($scope, myService)  
  11.              {  
  12.                 $scope.FirstName = myService.FirstName();  
  13.                 $scope.FullName = myService.FullName;  
  14.             });  
  15.             app.service('myService', function()  
  16.             {  
  17.                 varmyName = "Shiva";  
  18.                 this.FirstName = function()   
  19.                 {  
  20.                     return myName;  
  21.                 }  
  22.                 this.FullName = myName + " " + "shukla"  
  23.             });  
  24.         </script>  
  25. </head>  
  26. <body ng-app="app">  
  27.     <p>AngularJS Service</p>  
  28.     <div ng-controller="MemberController">  
  29.         <p>  
  30.             FirstName: {{FirstName}}  
  31.         </p>  
  32.         <p>  
  33.             FullName: {{FullName}}  
  34.         </p>  
  35.         </div>  
  36.         </body>  
  37.   
  38. </html>  
Output

output

When to use: It is a singleton object. Use it when you need to share a single object across the application.

Provider:

A provider is used to create a configurable service object. It returns value by using $get () function, $provide service has a number of methods for registering components with the $injector.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Provider Demo</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  7.         </script>  
  8.         <script>  
  9.             var app = angular.module('app', []);  
  10.             app.config(["myProviderServiceProvider", function(myProviderService)   
  11.              {  
  12.                 myProviderService.set("shiva""shukla");  
  13.             }]);  
  14.             app.controller("MemberController", function($scope, myProviderService)   
  15.             {  
  16.                 $scope.FirstName = myProviderService.FirstName();  
  17.                 $scope.LastName = myProviderService.LastName();  
  18.                 $scope.FullName = myProviderService.FullName;  
  19.             });  
  20.             app.provider('myProviderService', function()  
  21.              {  
  22.                 var myFName = "Shiva";  
  23.                 var myLName = "Shukla";  
  24.                 return {  
  25.                     set: function(fName, lName)   
  26.                   {  
  27.                         myFName = fName;  
  28.                         myLName = lName;  
  29.                     },  
  30.                     $get: function()  
  31.                   {  
  32.                         functiongetFName()  
  33.                         {  
  34.                             returnmyFName;  
  35.                         }  
  36.                         functiongetLName()  
  37.                         {  
  38.                             returnmyLName;  
  39.                         }  
  40.                         return  
  41.                         {  
  42.                             FullName: myFName + " " + myLName,  
  43.                             FirstName: getFName,  
  44.                             LastName: getLName  
  45.                         };  
  46.                     }  
  47.                 };  
  48.             });  
  49.         </script>  
  50. </head>  
  51. <body ng-app="app">  
  52.     <p>AngularJS Provider</p>  
  53.   
  54.   
  55.     <div ng-controller="MemberController">  
  56.         <p>  
  57.             FirstName: {{FirstName}} and LastName : {{LastName}}  
  58.         </p>  
  59.         <p>  
  60.             FullName: {{FullName}}  
  61.         </p>  
  62.         </div>  
  63.   
  64.         </body>  
  65.   
  66. </html>  
Output

output

When to use:

When you need to provide module-wise configuration for your service object before making it available.

Value:

You can also register a function as a value. Values are typically used as configuration which is injected into factories, services or controllers.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Value Demo</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  7.         </script>  
  8.         <script>  
  9.             var app = angular.module('app', []);  
  10.             app.controller("MemberController", function($scope, numberValue, stringValue, objectValue)  
  11.             {  
  12.                 $scope.numberValue = numberValue;  
  13.                 $scope.stringValue = stringValue;  
  14.                 $scope.objectValue = objectValue;  
  15.             });  
  16.             app.value("numberValue", 1000);  
  17.             app.value("stringValue""Hello Word");  
  18.             app.value("objectValue",   
  19.             {  
  20.                 objVal1: true,  
  21.                 objVal2: "My object Value"  
  22.             });  
  23.         </script>  
  24. </head>  
  25. <body ng-app="app">  
  26.     <p>AngularJS Value</p>  
  27.   
  28.     <div ng-controller="MemberController">  
  29.         <p>  
  30.             number Value: {{numberValue}}  
  31.             <br/> string Value: {{stringValue}}  
  32.             <br/> object Value : {{objectValue.objVal1}} and {{objectValue.objVal2}}  
  33.         </p>  
  34.         </div>  
  35.         </body>  
  36.   
  37. </html>  
Output:

output
Constant:

It is like a value. Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function and it cannot be overridden by an Angular decorator.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title>Constant Demo</title>  
  6.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  7.         </script>  
  8.         <script>  
  9.             var app = angular.module('app', []);  
  10.             app.controller('MemberController', function($scope, myConfig)  
  11.              {  
  12.                 $scope.myConfig = myConfig;  
  13.             });  
  14.             app.constant('myConfig',  
  15.             {  
  16.                 flag: true,  
  17.                 settings: "default"  
  18.             });  
  19.         </script>  
  20. </head>  
  21. <body ng-app="app">  
  22.     <p>AngularJS Constant</p>  
  23.     <div ng-controller="MemberController">  
  24.         <p>  
  25.             flag: {{myConfig.flag}}  
  26.             <br/> settings: {{myConfig.settings}}  
  27.         </p>  
  28.         </div>  
  29.   
  30.         </body>  
  31.   
  32. </html>  
Output:

output

Decorator:

A decorator can modify or encapsulate other providers. There is one exception and that a constant cannot be decorated.

  1. var app = angular.module('app', []);  
  2.   
  3. app.value('movieTitle''Airlift');  
  4.   
  5. app.config(function($provide)   
  6. {  
  7.     $provide.decorator('movieTitle', function($delegate)   
  8.     {  
  9.         return $delegate + ' – The rising';  
  10.     });  
  11. });  
  12.   
  13. app.controller('MyController', function(movieTitle)  
  14. {  
  15.     expect(movieTitle).toEqual('Airlift – the rising');  
  16. });  
Summary: 
  • All the providers are instantiated only once. That means that they are all singletons.
  • All the providers except constant can be decorated.
  • A constant is a value that can be injected everywhere. The value of a constant can never be changed.
  • A value is just a simple injectable value.
  • A service is an injectable constructor.
  • A factory is an injectable function.
  • A decorator can modify or encapsulate other providers except a constant.
  • A provider is a configurable factory.