Can Angular handle properties containing hyphens within them?

As I embark on creating my first complete Angular application, I encountered an interesting quirk. The model I am working with has a data structure that looks like this:

{
    id: "12345",
    host: {
        name: "someHostServer",
        ip-addresses: [
           "1.2.3.4",
           "10.11.12.13"
        ]
    }
}

When rendering a page and assigning this structure to 'data' in the context, it is done as follows:

ID: {{data.id}}


Host: {{data.host.name}}
IP Addresses:

<span ng-repeat="address in data.host.ip-addresses">
     {{address}}<br />
</span>

The ID and host name display correctly, but the addresses do not appear. Is this due to the hyphen in 'ip-addresses'? If so, is there a simple way to transform the data? The data is fetched from a basic $resource factory.

Answer №1

When retrieving an object property using the dot notation (.), it is important to note that property names cannot contain hyphens (-).

To access a property with a name containing a hyphen, you must use square brackets like this: ['property-name'].

<div ng-repeat="item in data.list['item-names']">
     {{item}}<br />
</div>

Answer №2

JSON does not accept properties with hyphens, causing errors in JavaScript even without Angular.

Try using this data format instead:

{ id: "12345", host: { name: "someHostServer, "ip-addresses": [ "1.2.3.4", "10.11.12.13" ] } }

To test it in Chrome Dev tools, use:

console.log({ "name": "someHostServer", "ip-addresses": [ "1.2.3.4", "10.11.12.13" ] });

However, if you use:

console.log({ id: "12345", host: { name: "someHostServer, ip-addresses: [ "1.2.3.4", "10.11.12.13" ] } });

You will encounter an error.

Once you make the necessary changes, your markup should be as follows:

IP Addresses: {{data.host['ip-address']}}

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

Prevent the router link from being enabled until the submit button has been clicked

On page one, there is a submit button that, when clicked, should enable a router link to navigate to page two. If the button is not clicked, the router link should remain disabled. I attempted to disable the event, but it did not work. Page Two There is ...

Search through an array of objects in mongoose to verify if it includes a collection of strings

If we imagine a scenario where I have the following data stored in my database: knights { name: 'Knightley', skills: [ { name: 'sword', level: 2 }, { name: 'shield', level: 1 } ] }, { name: & ...

Guide to including a promise.map (bluebird) within a nested promise chain

I'm currently using a chain to control flow and struggling to make promise.map within step2() wait for all generated promises to be resolved. Here's a visual representation of the flow I aim for: step1() step2() step2() ste ...

Discover potential routes to nodes using JavaScript

I need assistance displaying all potential node paths in JavaScript: var object = {"metadata":{"record_count":5,"page_number":1,"records_per_page":5},"records":[{"name":"Kitchen","id":666,"parent_id":0,"children":null},{"name":"Jewellery","id":667,"pare ...

Is there a way to dynamically change the height in jQuery/JavaScript?

I am encountering an issue with my embed code where the height changes randomly after a few seconds, depending on certain parameters. Here is an example of the code I am using: $( <embed></embed>) .attr("src", "http://www.bbs.com") ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...

Creating dynamic canvas elements with images using HTML and JavaScript

Currently, I am working on a unique project involving a canvas filled with dynamic moving balls. This project is an extension or inspired by the codepen project located at: https://codepen.io/zetyler/pen/LergVR. The basic concept of this project remains t ...

How can I update a PHP variable's value after a successful jQuery AJAX call?

I am facing an issue with my shopping cart implemented in Codeigniter where products are added using jQuery Ajax. The problem occurs when I try to display the total number of items in the cart on each page header. <?php echo $this->cart->total_it ...

Trouble with serving CSS files using Express static directory

In my app.js file, I have the following code: app.use(express.static(path.join(__dirname, '../public'))); This code snippet is from my main layout page: <link rel="stylesheet" href="/css/styles.css"> Despite trying various combinations, ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

Searching for a specific value in an array with jQuery: A step-by-step guide

I am looking to search for a specific value within an array and retrieve its index. Sample HTML: <div class="container"> <div class="col-md-6"> <div id="task0">Task0</div> </div> <div class="col-md-6"> &l ...

Having trouble applying CSS to multiple classes used in an AJAX call

I'm trying to utilize richfaces for some fast AJAX widgets, but I am encountering difficulties in setting CSS parameters for them. After inspecting the generated code, I found that the elements have the classes "rf-ds" and "rpds". Despite applying st ...

Does expressJS use the express() function as a global function?

Can anyone confirm if the express() function used in the second statement is a global function? I have searched my project folder but couldn't find its declaration. var express = require('express'); var app = express(); var fs = require("fs ...

update embed - new command

My code below creates a slash command and I'm attempting to update the embed every 10 seconds. const embed = new EmbedBuilder() .setAuthor({ name: track.title, iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) }) .setThumbna ...

Troubleshooting the issue of setting an Array as the scope in AngularJS and encountering

I'm currently utilizing AngularJS. Check out the Fiddle var myArray = [{firstName: 'Jane', lastName: 'Doe', age:29}, {firstName: 'John', lastName: 'Doe', age: 32}]; This is an example of HTML: <body ng-ap ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

Can you confirm the mobile type, please? Using JavaScript to display a div only once based on the mobile type

Is there a correct way to determine the type of mobile device I'm using? Are there alternative methods to check for the mobile type? Take a look at my approach in the code below. How can I test this using a tool? Does anyone have insights on checki ...

Implementing the display of bootstrap modal with error message upon page reload in CodeIgniter

Currently, I have a popup model that allows users to add a course name. In my Codeigniter controller, I have implemented form validation. If the validation fails, I reload the view with an error message displayed above the form input in the modal. However, ...

What is the best way to create pages that showcase 10 posts each?

Currently, I am facing a challenge with displaying 100 posts using the Fetch API on one single page. I am looking for a way to create separate pages where each page would showcase only 10 posts. Below is my existing JavaScript code: fetch('htt ...