我需要遍历看起来像
的嵌套json数组[
{
"title": "EPAM",
"technologies": [
"PHP",
".net",
"Java",
"Mobile",
"Objective-C",
"Python",
"Ruby"
],
"location": "Belarus",
"city": "Minsk"
},
{
"title": "Parallels",
"technologies": [
"PHP",
"Java",
"C++",
"iOS Development",
"C#",
"Ember.js"
],
"location": "Russia",
"city": "Moscow"
}
]
我想要的是遍历每个公司的技术列表,然后返回唯一值列表。但是,我无法访问控制器中公司阵列中的单个公司。到目前为止看起来像这样
var app = angular.module('app', []);
app.controller('CompaniesController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/companies.json').success(function(data) {
$scope.companies = data; // get data from json
$scope.techStack = []
$scope.companies = data.query(function(companies) {
console.log(companies); //I expected to see data here
});
});
}
]);
显然我做错了。
答案 0 :(得分:28)
对每个角色使用角度
var app = angular.module('app', []);
app.controller('CompaniesController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/companies.json').success(function(data) {
$scope.companies = data; // get data from json
angular.forEach($scope.companies, function(item){
console.log(item.technologies);
})
});
});
}
]);
答案 1 :(得分:6)
如果只需要在UI上显示嵌套数组,则可以在视图中直接显示 e.g。
<tr ng-repeat="i in Items">
<td valign="top">{{i.Value}}</td>
<td valign="top">
<table>
<tr ng-repeat="c in i.Children">
<td>{{c.Value}}</td>
</tr>
</table>
</td>
</tr>
答案 2 :(得分:3)
为了在AngularJS中循环遍历数组,您只需使用angular.forEach即可。例如,
angular.forEach(companiesList, function(company) {
//Here you can access each company.
});
我根据你的代码做了一个简单的演示,列出了#34;公司&#34;和独特的&#34;技术&#34;。
<强> DEMO 强>
答案 3 :(得分:2)
试试这个
var app = angular.module('app', []);
app.controller('CompaniesController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/companies.json').success(function(data) {
$scope.companies = data; // get data from json
$scope.techStack = []
angular.forEach($scope.companies, function(item){
$scope.techStack = item.technologies;
var uniqueTech = [];
for (var i = 0; i < $scope.techStack.length; i++)
{
if (uniqueTech.indexOf($scope.techStack[i]) == -1)
uniqueTech.push($scope.techStack[i]);
}
console.log("Unique Technologies : " + uniqueTech);
})
});
}
]);
答案 4 :(得分:0)
用户角度的foreach函数,用于循环数据。