Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs Constant value gets changed

I have a module named "app" in which I have defined a constant "PI", later in my controller when i am trying to change the value of constant it gets changed.

I am not able to Understand the purpose of constant in AngularJS.

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

app.controller('appCtrl', function(PI) {
    var radius = 4;
    PI=2;
    // calculate area of the circle
    console.log(PI);
    var area = PI * radius * radius; 
});
like image 484
Wasimakram Mulla Avatar asked Jan 29 '26 10:01

Wasimakram Mulla


1 Answers

You're not actually changing the value of the constant. You're changing the value of the lexically bound variable introduced through the dependency injected argument.

Look at the following example using the Javascript const keyword.

const PI = 3.14;

function area(pi, radius) {
  pi = 2;
  console.log('pi', pi);
  console.log('PI', PI);
  return pi * Math.pow(radius, 2);
}

Clearly pi will be logged as 2 but we haven't violated the constant nature of PI, we've just changed the binding of pi.

When you call a function, it introduces new variables into the scope, one for each parameter. You have no control over the binding of these variables—unlike regular variables which can be introduced with let, var and const.

If you inject your constant into another module, you'll see that the value hasn't been changed.

If you want to guarantee that the variable can't be rebound within the scope of the function that introduced it, you can re-introduce it with const.

app.controller('appCtrl', function(PI) {
  var radius = 4;
  const pi = PI;
  pi = 2;
  // calculate area of the circle
  console.log(pi);
  var area = PI * radius * radius; 
});

The purpose of const in Angular applications is to make a guarantee that the injected value will be the same, wherever and whenever you inject it.

like image 70
Dan Prince Avatar answered Jan 31 '26 04:01

Dan Prince