2

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 ?

David Dury
  • 5,537
  • 12
  • 56
  • 94
  • 1
    possible duplicate of [is there a way in Angularjs to define constants with other constants?](http://stackoverflow.com/questions/18494050/is-there-a-way-in-angularjs-to-define-constants-with-other-constants) – flup Apr 10 '15 at 06:47

2 Answers2

1

Sure:

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

app.constant('appHelper', appHelper);
app.constant('appHelper2', {
    fullName: appHelper.first + '' + appHelper.last
});
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

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;
});
Community
  • 1
  • 1
Jeeva J
  • 3,173
  • 10
  • 38
  • 85