Is it possible to pass a constant to another constant within Angular?

Is there a way to define a constant in Angular that depends on another constant being passed to it? See this example:

angular
  .constant("names", ["Bob", "Jane"])
  .constant("friends", ["names", getFriends]);

function getFriends(names) {
  var friends = {};

  names.forEach(function(name) {
    friends[name] = { firstName: name };
  });

  return friends;
}

The names constant defines an array of names passed to a function to generate object literals.

While this code doesn't work as expected, is there a way to achieve this concept? One approach could be like this...

var names = ["Bob", "Jane"];

angular
  .constant("names", names)
  .constant("friends", getFriends())
  .controller("myController", MyController);

function getFriends() {
  var friends = {};

  names.forEach(function(name) {
    friends[name] = { firstName: name };
  });

  return friends;
}

... however, I prefer to avoid this method (I prefer to have constants defined in separate JS files).

Note: The reason for not using a factory for friends is to make both constants available during the configuration phase.

Answer №1

In the config phase of the module, you have the opportunity to perform some processing with the available constants. Check out the AngularJS documentation for more information:

angular.module('myModule').constant('names', ['Bob', 'Jane']);
angular.module('myModule').constant('friends', {});

angular.module('myModule').config(function(names, friends) {
  names.forEach(function(name) {
    // Modifying the friends constant
    friends[name] = { firstName: name };
  });
});

Remember, you can't change the object that the constant refers to, but you can make changes to the object itself.

Answer №2

Unfortunately, the answer remains a resounding No - passing a constant to another constant is not allowed.

My solution was to opt for a provider approach instead:

angular
    .module("myApp", [])
    .constant("animals", ["Cat", "Dog"])
    .provider("pets", PetsProvider);

PetsProvider.$inject = ["animals"];

function PetsProvider(animals) {
    var self = this;
    self.pets = {};

    // ----- 8< -----  

    self.$get = [function() {
      return self.pets;  
    }];    
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AngularJs for searching strings in a function

I'm currently working on implementing a search function using angularjs. However, I have encountered an issue where the function returns results based on my search query but when I delete the search query, it displays all objects in the set. Here&apos ...

Storing notes using HTML5 local storage

I recently developed a unique note-taking web application where users can create multiple notes and switch between them using tabs on the left side. My next step was to implement local storage for saving these notes, so I inserted the following code: $(d ...

Generating a Vue JS component on the fly

How can I dynamically create a component in Vue JS on click and then route to that component in a single click event? I am using Vue 3 and my current code snippet looks like this: methods:{ routerClick(value){ console.log("The number is "+value) ...

Ways to determine if the backbone.js model has been emptied

I often find myself wondering how to determine if a model has been cleared or is empty. For example, if I set the model with: model.set({name:'this is a test', id:1}); and then clear it with: model.clear(); ...

What makes componentDidMount the ideal location to initiate AJAX requests?

It is quite common to see AJAX requests being fired at the componentDidMount hook in many React projects. However, I find it hard to understand this suggested practice. For example, consider a component where the AJAX request depends on a prop from the pa ...

Switch on/off the active class for menu items in a list using VueJS

When I click on a menu item, I want the active class to be triggered only for that specific item and removed for the others. So far, I have written this code: <template> <nav class="navbar"> <div class="navbar__brand"> <ro ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

Troubleshooting chained select boxes using jQuery, PHP, and database integration

Although many chained selects are typically done using JSON, I prefer to utilize my database for this purpose. However, I seem to be encountering an issue where the second select box is not loading properly. Instead of displaying the expected content, it&a ...

The functionality of the Bootstrap carousel may be compromised when initialized through JavaScript

Why isn't the Bootstrap carousel working in the example below? It starts working when I paste it into .content <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script sr ...

Issue encountered: Model binding is not functioning properly in AngularJS and MVC4 collaboration

Recently, I delved into learning AngularJS and encountered a simple issue. I have a controller in JavaScript that showcases candidate results, and my goal is to display the specific details of each candidate. //Fetches Candidate List var Listcandidates = ...

Arranging the data in the table by alternating rows using Datatables

I need to organize my data in a way that includes an additional row for descriptive information, but this particular row should not be sorted. It is crucial for understanding the rest of the data, so hiding or showing it is not an option. Is it possible t ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...

What is the best way to extract information from a JavaScript page when the content is identified by a reference?

If you're looking for the website, you can visit . It's primarily in Chinese, but that may not be relevant to the topic at hand. Currently, I am able to extract all the content from this page and now I'm interested in moving on to the next ...

Exploring the Possibilities with NodeJS and Socket.IO

I've encountered an interesting issue with my use of NodeJS and Socket.io. The server receives data through ZeroMQ, which is working perfectly fine. However, when there are a large number of connected clients (over 100), it appears that there is a de ...

In JavaScript, an HTTP request file includes a JavaScript variable

I am currently working on a Node.js project that involves making an HTTP request to fetch a JavaScript file. For example, let's say we have a file named a.js: var a = 'i am a.js'; var b = 'please convert me to js'; Here is the a ...

"Encountering an issue with Express.json where it fails to parse the

Receiving JSON POST data from an IoT API that includes multipart form-data. Occasionally, an image file may be included but I only want to focus on the JSON part: POST { host: '192.168.78.243:3000', accept: '*/*', 'content-le ...

What is the process for altering a route in React 18?

Previously, I relied on the withRouter Higher Order Component (HOC) along with props.history.push() function to manage routes. However, with the introduction of React 18, these options are no longer available. My current task involves editing a post and ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...

What is the best method to toggle between inline div elements in AngularJS? Should I use ng-switch, ng-hide, or ng-show?

I am looking for a way to change the orientation of a div based on a specific event trigger. This could be done using onclick, ng-switch, ng-show, or ng-hide. I would appreciate it if someone could demonstrate a working example without utilizing ng-include ...

I encountered an issue where the bootstrap $uibModal was not defined and I couldn't use it

I've been attempting to implement Bootstrap into my project, but I'm encountering difficulties. Below is a snippet of my app.js file: I am looking to incorporate Bootstrap with my users module. angular.module('Authentication', []); a ...