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

