iiminov iiminov - 1 year ago 166
AngularJS Question

Dynamic constants within 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
operation or just
.constant('Groupid', function(){})
. But the latter doesn't work becuase
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

var cusObj = { GroupId: getGroupId(), };
var myApp = angular.module('myApp', ['ui.router', 'ngResource', 'cusObj']);

Answer Source

A decorator can modify or encapsulate other providers. There is one exception and that a constant cannot be decorated. so you can use value from angular.

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

app.value('movieTitle', 'The Matrix');

app.config(function ($provide) {
  $provide.decorator('movieTitle', function ($delegate) {
    return $delegate + ' - starring Keanu Reeves';

app.controller('MyController', function (movieTitle) {
  expect(movieTitle).toEqual('The Matrix - starring Keanu Reeves');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download