You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS中键名含空格时如何获取对应属性值?

Hey there! Great question—this is a common gotcha when dealing with object keys that have spaces in AngularJS (and JavaScript in general).

The Problem

Your original code uses dot notation ({{lang.Web Framework}}) to access the key with a space, but JavaScript doesn't allow spaces in property names when using dot notation. The interpreter sees Web as one property and Framework as an unrelated identifier, which causes an error.

The Solution: Bracket Notation

To access keys with spaces, you need to use bracket notation instead of dot notation. Here's how you'd rewrite that part:

Web Framework: {{lang['Web Framework']}}<br>

Corrected Full Code

Here's your complete AngularJS code with the fix applied:

<div ng-app="">
  <div ng-init="language=[{'language': 'Python', 'Web Framework': 'Django'}, {'language': 'PHP','Web Framework': 'Laravel'}]">
  </div>
  <p ng-repeat="lang in language">
    Language: {{lang.language}} <br>
    Web Framework: {{lang['Web Framework']}}<br>
  </p>
</div>

Why This Works

AngularJS expressions are a subset of JavaScript, so they follow the same rules for object property access. Bracket notation lets you use strings (including those with spaces) to reference object keys directly, which bypasses the restriction on valid identifiers that dot notation has.

A Quick Note

While this works perfectly, it's still a good practice to avoid spaces in object keys when you can—using camelCase (like webFramework) makes your code cleaner and avoids needing bracket notation. But since you specifically asked to keep the space, bracket notation is the way to go!

内容的提问来源于stack exchange,提问作者Ankur Ranjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:56:23