vinoth
vinoth

Reputation: 106

Difference between constant and value in AngularJS

What is difference between constant and value? we are able to change both values.

var app = angular.module(‘myApp’,[]);
app.constant(‘appName’,‘My App’);
app.value(‘applicationName’,‘Sample’);

Upvotes: 4

Views: 6927

Answers (3)

Monojit Sarkar
Monojit Sarkar

Reputation: 2451

1) constant's value can not be change 2) value's data can be change

1) constant can be injected any where 2) value can be injected in controller, service, factory but can't be injected in config.

sample

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

app.value('greeting', 'Hello');

app.config(function(greeting){
    var radius = 4;
    //PI can be injected here in the config block
    var perimeter = 2 * PI * radius;
});

the below code will give error because trying to inject value into config.

Upvotes: 2

Victor Orletchi
Victor Orletchi

Reputation: 497

good explain is here:

Constants are great for values that never change. If you need to access values within config function calls to configure routes or anything else when your application first starts, constants are what you should use.

Values are great for pieces of data that can and will change. As shown above user data or anything else where you simply want to keep a reference to a changing value stored globally without creating a messy global variable.

full article: Constants & Values: Global Variables In AngularJS The Right Way

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172548

Constants can put anywhere whereas Values cannot be added anywhere. Also constants cannot be intercepted by decorators whereas values can be intercepted by decorators.

Also refer: Value and Constants

The difference between a value and a constant service is that the former can only be injected (and thus be used) in a service or a controller while the latter can also be injected into a module configuration function.. (I will discuss the module configuration function in a future post).

Upvotes: 1

Related Questions