0

I am working with AngularJs and I am initializing a variable in the ng-init of that model.

<body ng-init="allowedState=2" ng-controller="amCtrl">
</body>

Now what I want is to declare a constant using this variable which will then be shared within the app.

angular.module('amModule').constant('temp', ?)

I am trying to figure this out and I am now wondering if it's even possible?

Darshan Patel
  • 2,839
  • 2
  • 25
  • 38
Amna Tariq
  • 135
  • 1
  • 9
  • you can add those values to `$rootScope` to access anywhere in the app. Although it is not a good practice. But for simple scenarios, you can add variables in `$rootScope` – Muhammad Usman Nov 13 '17 at 10:36

2 Answers2

0

Yes you can do the above way

angular.module('amModule').constant('allowedState',2);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Using ng-init;

ng-init="loader(); firstName = 'John'"

It's better not to use the ng-init instead use below methods;

You can constants or values for initializing variables; Official angular doc link

Example: With Constant:

var app = angular.module('myApp', []);
app.constant('appName', 'Application Name');

app.controller('TestCtrl', ['appName', function TestCtrl(appName) {
    console.log(appName);
}]);

With Values:

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

app.value('usersOnline', 0);
app.controller('TestCtrl', ['usersOnline', function TestCtrl(usersOnline) {
    console.log(usersOnline);
    usersOnline = 15;
    console.log(usersOnline);
}]);

Also, using service is good solution; Using rootScope and service method

Thanks,

Rajan Maharjan
  • 4,398
  • 2
  • 16
  • 26