本文介绍了ng-repeat 在对象上部分循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个简单的程序(在概念上)但不幸的是.我已经解决了这个问题,几天的谷歌搜索没有产生任何结果.
我正在尝试遍历一个对象,并且它都是子对象.我已经用两个 ng-repeat
完成了这项工作,理论上看起来非常合理且万无一失
这是我当前的代码:
(function() {var CHEAT = angular.module('cheat', []);CHEAT.controller('maps', function($scope) {$scope.search = "";$scope.range = {全球":{"$": "M",M":{"z": "q"}},其他": {S":{'c':猫"}}};$scope.type = function(obj) {返回类型为 obj;};});}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div id="info" ng-app="cheat" ng-controller="maps"><div ng-repeat="(res, prop) 在范围内">{{prop}} =<div ng-repeat="(key,test) in prop">{{关键测试}}
如果你运行代码,它看起来就像刚刷过 angular:
"$": "M"
这几乎就像 angular 只是忽略了任何值不是对象的东西.
解决方案
您在 Angular 中偶然发现了一个问题.
以美元符号 ($) 开头的键不会被 ng-repeat 识别($ 是 angular 和其他前端库中的保留字符).
链接到 Github 问题(目前似乎不-修复):
示例小提琴:http://jsfiddle.net/takvg/4/
从上面提到的github问题,frfancha有一个解决方法:
解决方法很简单:只需在 Object.keys(myObject) 上进行 ng-repeat
例如:
$scope.thing = {全球":{"$": "M",M":{"z": "q"}},其他": {S":{'c':猫"}}};$scope.range = Object.keys($scope.thing);
您将处理一个数组而不是一个对象,因此您的 ng-repeat 需要稍作更改.
I am developing a simple program (in concept) but unfortunately. I have com upon the problem and days of googling have not resulted in anything.
I'm trying to loop through an object, and all it's children. I've done this with two ng-repeat
s which in theory seems pretty sound and fool-proof
Here's my current code:
(function() {
var CHEAT = angular.module('cheat', []);
CHEAT.controller('maps', function($scope) {
$scope.search = "";
$scope.range = {
"Globals": {
"$": "M",
"M": {
"z": "q"
}
},
"Other": {
"S": {
'c': "cat"
}
}
};
$scope.type = function(obj) {
return typeof obj;
};
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="info" ng-app="cheat" ng-controller="maps">
<div ng-repeat="(res, prop) in range">
{{prop}} =
<div ng-repeat="(key,test) in prop">
{{key}}: {{test}}
</div>
</div>
</div>
If you run the code, it seems like angular just brushed over the:
"$": "M"
It's almost as if angular just dismisses anything whose value isn't an object.
解决方案
You've stumbled across a gotcha in Angular.
Keys that begin with dollar sign ($) will not be recognized by an ng-repeat ($ is a reserved character in angular and other frontend libraries).
Link to the Github issue (currently seems to be a do-not-fix):
Example fiddle:http://jsfiddle.net/takvg/4/
From the github issue mentioned above, there is a workaround from frfancha:
For instance:
$scope.thing = {
"Globals": {
"$": "M",
"M": {
"z": "q"
}
},
"Other": {
"S": {
'c': "cat"
}
}
};
$scope.range = Object.keys($scope.thing);
You'll be dealing with an array instead of an object, so your ng-repeat will need to change a little bit.
这篇关于ng-repeat 在对象上部分循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!