我在AngularJS控制器这样的数组:如何根据给定的信息找到一个数组对象?
$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]
我有一个名为“露西”,我怎么能得到这个名字的年龄在控制器(未在HTML)?
我在AngularJS控制器这样的数组:如何根据给定的信息找到一个数组对象?
$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]
我有一个名为“露西”,我怎么能得到这个名字的年龄在控制器(未在HTML)?
我在这里创建了一个简单的结果,只是年龄,以及多个结果。
这也可以一个过滤器,这是在这里的角部位文件内实施:https://docs.angularjs.org/api/ng/filter/filter
https://plnkr.co/edit/OFRMzpQrZfTOnaFyJP7Z?p=info
angular.module('plnk',[]).controller('plnkCtrl', function($scope){
// Note, I added a second Joey here to test the multiple function.
// For output, check the browser console.
$scope.persons = [{name:'Joey', age:'27'},{name:'Joey', age:'28'},{name:'Lucy', age:'22'}]
console.log('Single -> ', getAgeSingle('Lucy'));
console.log('Multiple ->',getAgeMultiple('Joey'));
function getAgeMultiple(personLookup) {
var results = [];
angular.forEach($scope.persons,function(person){
if (person.name === personLookup) {
results.push(person);
// or results.push(person.age) for age only
}
});
return results;
}
function getAgeSingle(personLookup) {
var result = '';
angular.forEach($scope.persons,function(person){
if (person.name === personLookup && !result) {
result = person.age;
}
});
return result;
}
});
如果通过范围要循环:
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}]
function getAge(name) {
angular.forEach($scope.persons, function (value, index) {
if (value.name === name) {
return parseInt(value.age, 10);
}
});
return undefined;
}
的HTML方式:
<div ng-app="myApp" ng-controller="MainCtrl">
<table>
<tr ng-repeat="person in persons">
<td>Name: {{person.name}} Age: {{person.age}}</td>
</tr>
</table>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}];
});
这并不做任何过滤按OP问题。 OP还表示,他们想要在控制器中检索..非HTML – charlietfl
@charlietfl更新以包括过滤器。 – fuzz
只是循环阵列上,并检查,这样:
function getAge(name)
{
for (var i = 0; i < $scope.persons.length; i++)
{
var person = $scope.persons[i];
if (person.name === name)
{
return parseInt(person.age, 10);
}
}
return undefined;
}
这有几个警告 - 如果你有欺骗,你只会得到第一个,它会在线性时间运行。如果你控制数据源,最好使用JS对象/ hashmap/dictionary /无论你想调用它。
我喜欢这个,因为它占多个同名的人。 – fuzz