David Dury
David Dury

Reputation: 5717

AngularJs use constant in other constant

If I declare 1 constant like this:

app.constant('appHelper', {
    first: 'Firstname',
    last: 'Lastname'
});

and then try to use it in a second constant like this:

app.constant('appHelper2', {
    fullName: appHelper.first + '' + appHelper.last
});

doesn't work. Error: appHelper is undefined.

Any ideas how can I do that ?

Upvotes: 2

Views: 632

Answers (2)

Jeeva J
Jeeva J

Reputation: 3249

Reference and Credits:

is there a way in Angularjs to define constants with other constants?

http://michalostruszka.pl/blog/2012/12/23/angular-better-constant-values/

Based on this, the following may be suitable for you.

var myApp = angular.module("exampleApp",[]);

myApp.constant('HELPER', (function() {
  // Define your variable
  var appHelper = {
    first: 'Firstname',
    last: 'Lastname'
};
  // Use the variable in your constants
  return {
    appHelper:appHelper,
    fullName: appHelper.first + '' + appHelper.last
  }
})());

myApp.controller("ExampleCtrl", function(HELPER){
  $scope.firstname = HELPER.appHelper.firstname;
  $scope.fullName = HELPER.fullName;
});

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691943

Sure:

var appHelper = {
    first: 'Firstname',
    last: 'Lastname'
}

app.constant('appHelper', appHelper);
app.constant('appHelper2', {
    fullName: appHelper.first + '' + appHelper.last
});

Upvotes: 1

Related Questions