Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic constants within AngularJs

Tags:

angularjs

For anyone with deeper knowledge of constants is it possible to somehow assign it dynamically?

I know this is a silly question but up to this point I have been using a constant to define a parameter:

myApp.constant('Groupid', 10);

While this works fine in development in production this parameter will change based on the group. Luckily this can be determined before, at, or during module initialization.

So, I was thinking something that would be able to set this parameter in the .run() or .config() operation or just .constant('Groupid', function(){}). But the latter doesn't work becuase constant only accepts a value/object as its second argument.

As the only alternative that can see I could use a directive but it would be evaluated way too many times unnecessarily between all service calls. While it is a fairly light and static function but still to be called so many times... I'd prefer a constant assignment.

Is that just something I have to live with for the time being or there is light at the end of the tunnel?

In Addition

Just as I posted this question another idea came to mind. Is it possible to pass in a custom value/object from outside into .module?

var cusObj = { GroupId: getGroupId(), };
var myApp = angular.module('myApp', ['ui.router', 'ngResource', 'cusObj']);
like image 394
iiminov Avatar asked Dec 13 '25 23:12

iiminov


1 Answers

Providers allow complex creation function and configuration options. A provider is actually a configurable factory. The provider accepts an object or a constructor. You can read about all the options here

app.provider('movie', function () {
    var version;
    return {
        setVersion: function (value) {
            version = value;
        },
        $get: function () {
            return {
                title: 'The Matrix' + ' ' + version
            }
        }
    }
});

app.config(function (movieProvider) {
    movieProvider.setVersion('Reloaded');
});
like image 89
Touhid Alam Avatar answered Dec 15 '25 13:12

Touhid Alam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!