简体   繁体   中英

Initialize Constant Using ng-init Variables in AngularJs

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?

是的,您可以按照上述方式进行

angular.module('amModule').constant('allowedState',2);

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM