在Angular指令中使用JSON方括号表示法来访问值

时间:2014-10-03 11:19:06

标签: angularjs

我有一个JSON对象,它在namespace:key形式的某些键中包含名称空间。因此,我需要使用方括号表示法而不是点符号来访问其值。

我正在尝试使用一些角度指令/过滤器来处理数据,在本例中我将使用filter,但问题似乎也是在指令中使用括号表示法的横向。 / p>

这是我的榜样:

ng-repeat with HTML中的过滤器:

<ul>
  <li ng-repeat="item in items | filter:{properties['namespace:status']}">
    {{item.name}}
  </li>
</ul>

$ scope.items内容:

{
  "properties":{
    "namespace:status":"A",
    "name":"Potato",
    // ...
  },
  // ...
},
{
  "properties":{
    "namespace:status":"B",
    "name":"Carrot",
    // ...
  },
  // ...
},
{
  "properties":{
    // Note that it doesn't contain the namespace attribute
    "name":"Bean",
    // ...
  },
  // ...
}

预期呈现的HTML:

<ul>
  <li>Potato</li>
  <li>Carrot</li>
</ul>

实际结果

Error: [$parse:syntax] Syntax Error: Token '[' is unexpected, expecting [:] at column X of the expression [items | filter:{properties['namespace:status']}] starting at [['namespace:status']}].

指示我出现语法错误。

我的问题是,相同的表达式{{properties['namespace:status']}}确实符合模板中的语法,所以我不确定我做错了什么,或者指令是否只能处理括号表示法。

如果是后者,有关如何在不重写JSON的情况下解决这个问题的任何建议吗?

1 个答案:

答案 0 :(得分:1)

您应该像这样指定一个对象键

<ul>
  <li ng-repeat="item in items | filter:{prop: properties['namespace:status']}">
    {{item.name}}
  </li>
</ul>

您可以在此处查看http://codepen.io/anon/pen/BslpA

但是你应该知道angularjs不能通过对象属性数组进行过滤,它只能是数组。