0

I know AngularJS has some Dependency Injection techniques. So if the code is and mainApp.value("defaultInput", 5); passes the data to the controller.

//define a module
var mainApp = angular.module("mainApp", []);

//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...

//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
   $scope.number = defaultInput;
   $scope.result = CalcService.square($scope.number);

   $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
   }
});

Why not just declare var defaultInput = 5 before the model definition? Why create a new syntactical sugar in AngularJS with value? Why create totally something new when you already have an option? Why complicate things?

  • You shouldn't do either of those options. Instead you should store global values in a service. – BShaps Jul 06 '18 at 19:46
  • Can you elaborate on why I should do that? Because the following website shows this is one of the plausible options: https://www.tutorialspoint.com/angularjs/angularjs_dependency_injection.htm –  Jul 06 '18 at 19:55
  • 1
    For in-depth discussion about DI, see [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) at Wikipedia, [Inversion of Control](http://martinfowler.com/articles/injection.html) by Martin Fowler, or read about DI in your favorite software design pattern book. See also [AngularJS Developer Guide - Why Dependency Injection?](https://docs.angularjs.org/guide/di#why-dependency-injection-). – georgeawg Jul 06 '18 at 20:13
  • I'm voting to close this question as off-topic because it is a discussion about the pros and cons of Dependency Injection and not a question about a specific software problem. Possible duplicate of [What is dependency injection and when/why should or shouldn't it be used?](https://stackoverflow.com/questions/130794/what-is-dependency-injection) – georgeawg Jul 06 '18 at 20:28
  • @mvr950 There are a few reasons, but the simple answer is that using factories is a more powerful and secure method for global variables. Some examples of those benefits are that AngularJS factories are singletons, encapsulation, and they don't get initialized unless necessary (i.e. memory benefits). – BShaps Jul 06 '18 at 22:53

1 Answers1

1

Yes you can do that, the difference is that,

if you use var, the context is available only to the particular controller. if you want to declare in another controller you need to use another var and assign the value.

When you use .value, it behaves as a global constant , so whenever you need to use the value, you can just inject the value and use across controllers.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396