[英]Access AngularJS scope object using a different scope object as the key
I am iterating through an array of person objects using ng-repeat
Say the array looks like this: 我正在使用
ng-repeat
遍历人员对象数组。说该数组如下所示:
[{
"display_name": "John Smith",
"status": "part-time",
"bio": "I am a person. I do people stuff.",
}, {
"display_name": "Jane Doe",
"status": "full-time",
"bio": "I am yet another person.",
}, ...]
Meanwhile, I have another number_list
object that looks like this (note the uppercase): 同时,我还有另一个
number_list
对象,看起来像这样(注意大写):
{
"JOHN SMITH": 12,
"JANE DOE": 34,
...
}
In the HTML, I am able to interpolate from each person object like so: 在HTML中,我可以像这样从每个人对象插入:
<p>
Person Name: {{ person.display_name }}
Person Bio: {{ person.bio }}
...
</p>
But I'd also like to interpolate from the second object, accessing the value where the key matches the person object I'm on, like so: 但我也想从第二个对象进行插值,访问键与我所在的人物对象匹配的值,如下所示:
<p>
...
Person Number: {{ number_list['{{ person.display_name | uppercase }}'] }}
</p>
I am using the EMCAScript Bracket notation rather than the dot notation to specify the key, because of the spaces in the key names of number_list
(eg "JOHN SMITH"
) but I get nothing out of that interpolation. 由于number_list的键名中有
number_list
(例如"JOHN SMITH"
),因此我使用EMCAScript括号表示法而不是点表示法来指定键,但是从插值中我什么也没得到。
I have confirmed that if I type in a name eg {{ number_list['JOHN SMITH'] }}
that I am able to interpolate the value -- 12
in this example. 我已经确认,如果我输入一个名称,例如
{{ number_list['JOHN SMITH'] }}
,则可以插值-在此示例中为12
。 This means the issue doesn't have to do with scope or anything like that as far as I can tell. 就我所知,这意味着此问题与范围或任何类似内容无关。
Nested interpolation with double curly braces ( {{ }}
) is not supported by the AngularJS framework. AngularJS框架不支持带有双花括号(
{{ }}
)的嵌套插值。 If you want to run more complex code, you should make it a controller method and call the method from your view. 如果要运行更复杂的代码,应将其设置为控制器方法,然后从视图中调用该方法。
<p ng-repeat="person in persons">
...
̶P̶e̶r̶s̶o̶n̶ ̶N̶u̶m̶b̶e̶r̶:̶ ̶{̶{̶ ̶n̶u̶m̶b̶e̶r̶_̶l̶i̶s̶t̶[̶'̶{̶{̶ ̶p̶e̶r̶s̶o̶n̶.̶d̶i̶s̶p̶l̶a̶y̶_̶n̶a̶m̶e̶ ̶|̶ ̶u̶p̶p̶e̶r̶c̶a̶s̶e̶ ̶}̶}̶'̶]̶ ̶}̶}̶
Person Number: {{ ::personNumber(person.display_name) }}
</p>
$scope.personNumber = function(name) {
return $scope.number_list[name.toUpperCase()];
};
You can also use filter
to personNumber
for an object: 您还可以对对象的
personNumber
使用filter
:
app.controller("ctrl", function($scope){
$scope.persons = [...];
$scope.number_list = [...];
})
app.filter("personNumber", function(){
return function(array, name){
return array[name.toUpperCase()];
}
})
<p ng-repeat="person in persons">
...
Person Number: {{person.display_name | personNumber: number_list}}
</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.